From 73b9f890ea5fcde40e0bbc85570b75cd29e8fd21 Mon Sep 17 00:00:00 2001 From: Alexandru Fikl Date: Sun, 17 Mar 2024 13:44:27 +0200 Subject: [PATCH 1/2] style: add the Qt .clang-format file --- .clang-format | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..2fa7c0b --- /dev/null +++ b/.clang-format @@ -0,0 +1,114 @@ +# Copyright (C) 2016 Olivier Goffart +# +# You may use this file under the terms of the 3-clause BSD license. +# See the file LICENSE from this package for details. + +# This is the clang-format configuration style to be used by Qt, +# based on the rules from https://wiki.qt.io/Qt_Coding_Style and +# https://wiki.qt.io/Coding_Conventions + +--- +# Webkit style was loosely based on the Qt style +BasedOnStyle: WebKit + +Standard: c++17 + +# Column width is limited to 100 in accordance with Qt Coding Style. +# https://wiki.qt.io/Qt_Coding_Style +# Note that this may be changed at some point in the future. +ColumnLimit: 100 +# How much weight do extra characters after the line length limit have. +# PenaltyExcessCharacter: 4 + +# Disable reflow of some specific comments +# qdoc comments: indentation rules are different. +# Translation comments and SPDX license identifiers are also excluded. +CommentPragmas: "^!|^:|^ SPDX-License-Identifier:" + +# We want a space between the type and the star for pointer types. +PointerBindsToType: false + +# We generally use "template <" with space. +SpaceAfterTemplateKeyword: true + +# We want to break before the operators, but not before a '='. +BreakBeforeBinaryOperators: NonAssignment + +# Braces are usually attached, but not after functions or class declarations. +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + +# When constructor initializers do not fit on one line, put them each on a new line. +ConstructorInitializerAllOnOneLineOrOnePerLine: true +# Indent initializers by 4 spaces +ConstructorInitializerIndentWidth: 4 + +# Indent width for line continuations. +ContinuationIndentWidth: 8 + +# No indentation for namespaces. +NamespaceIndentation: None + +# Allow indentation for preprocessing directives (if/ifdef/endif). https://reviews.llvm.org/rL312125 +IndentPPDirectives: AfterHash +# We only indent with 2 spaces for preprocessor directives +PPIndentWidth: 2 + +# Horizontally align arguments after an open bracket. +# The coding style does not specify the following, but this is what gives +# results closest to the existing code. +AlignAfterOpenBracket: true +AlwaysBreakTemplateDeclarations: true + +# Ideally we should also allow less short function in a single line, but +# clang-format does not handle that. +AllowShortFunctionsOnASingleLine: Inline + +# The coding style specifies some include order categories, but also tells to +# separate categories with an empty line. It does not specify the order within +# the categories. Since the SortInclude feature of clang-format does not +# re-order includes separated by empty lines, the feature is not used. +SortIncludes: false + +# macros for which the opening brace stays attached. +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH, forever, Q_FOREVER, QBENCHMARK, QBENCHMARK_ONCE ] + +# Break constructor initializers before the colon and after the commas. +BreakConstructorInitializers: BeforeColon + +# Add "// namespace " comments on closing brace for a namespace +# Ignored for namespaces that qualify as a short namespace, +# see 'ShortNamespaceLines' +FixNamespaceComments: true + +# Definition of how short a short namespace is, default 1 +ShortNamespaceLines: 1 + +# When escaping newlines in a macro attach the '\' as far left as possible, e.g. +##define a \ +# something; \ +# other; \ +# thelastlineislong; +AlignEscapedNewlines: Left + +# Avoids the addition of a space between an identifier and the +# initializer list in list-initialization. +SpaceBeforeCpp11BracedList: false + +--- +# Use the Google-based style for .proto files. +Language: Proto +BasedOnStyle: Google +IndentWidth: 4 +ColumnLimit: 100 From bfa072adba9a0817ddd9a86ae40a556a318f2cc4 Mon Sep 17 00:00:00 2001 From: Alexandru Fikl Date: Sun, 17 Mar 2024 13:44:55 +0200 Subject: [PATCH 2/2] style: apply clang-format to the whole codebase --- app/aboutdialog.cpp | 75 +- app/aboutdialog.h | 4 +- app/assistantcontroller.cpp | 86 +- app/assistantcontroller.h | 10 +- app/configappearancewidget.cpp | 371 +++--- app/configappearancewidget.h | 60 +- app/configdialog.cpp | 86 +- app/configdialog.h | 28 +- app/configeditorwidget.cpp | 404 ++++--- app/configeditorwidget.h | 38 +- app/configgeneralwidget.cpp | 178 +-- app/configgeneralwidget.h | 20 +- app/configpreviewwidget.cpp | 63 +- app/configpreviewwidget.h | 12 +- app/editgotolinewidget.cpp | 40 +- app/editgotolinewidget.h | 22 +- app/editindentwidget.cpp | 90 +- app/editindentwidget.h | 32 +- app/editreplacecurrentwidget.cpp | 72 +- app/editreplacecurrentwidget.h | 28 +- app/editreplacewidget.cpp | 146 ++- app/editreplacewidget.h | 32 +- app/ktikzapplication.cpp | 188 ++- app/ktikzapplication.h | 14 +- app/linenumberwidget.cpp | 140 +-- app/linenumberwidget.h | 22 +- app/loghighlighter.cpp | 116 +- app/loghighlighter.h | 36 +- app/logtextedit.cpp | 38 +- app/logtextedit.h | 20 +- app/main.cpp | 210 ++-- app/mainwindow.cpp | 1666 ++++++++++++++------------- app/mainwindow.h | 303 +++-- app/tikzcommandinserter.cpp | 1169 ++++++++++--------- app/tikzcommandinserter.h | 97 +- app/tikzcommandwidget.cpp | 6 +- app/tikzcommandwidget.h | 6 +- app/tikzdocumentationcontroller.cpp | 52 +- app/tikzdocumentationcontroller.h | 8 +- app/tikzeditor.cpp | 1046 +++++++++-------- app/tikzeditor.h | 142 +-- app/tikzeditorhighlighter.cpp | 246 ++-- app/tikzeditorhighlighter.h | 40 +- app/tikzeditorview.cpp | 1070 ++++++++--------- app/tikzeditorview.h | 166 +-- app/tikzeditorviewabstract.h | 13 +- app/tikzktexteditorcompletion.cpp | 146 ++- app/tikzktexteditorcompletion.h | 64 +- app/tikzktexteditorview.cpp | 84 +- app/tikzktexteditorview.h | 51 +- app/usercommandeditdialog.cpp | 187 ++- app/usercommandeditdialog.h | 30 +- app/usercommandinserter.cpp | 84 +- app/usercommandinserter.h | 28 +- common/mainwidget.h | 17 +- common/templatewidget.cpp | 193 ++-- common/templatewidget.h | 38 +- common/textcodecprofile.h | 21 +- common/tikzpreview.cpp | 542 ++++----- common/tikzpreview.h | 126 +- common/tikzpreviewcontroller.cpp | 678 +++++------ common/tikzpreviewcontroller.h | 110 +- common/tikzpreviewgenerator.cpp | 941 +++++++-------- common/tikzpreviewgenerator.h | 120 +- common/tikzpreviewmessagewidget.cpp | 81 +- common/tikzpreviewmessagewidget.h | 22 +- common/tikzpreviewrenderer.cpp | 24 +- common/tikzpreviewrenderer.h | 16 +- common/utils/action.cpp | 50 +- common/utils/action.h | 18 +- common/utils/colorbutton.cpp | 48 +- common/utils/colorbutton.h | 32 +- common/utils/colordialog.h | 18 +- common/utils/combobox.cpp | 12 +- common/utils/combobox.h | 16 +- common/utils/file.cpp | 270 +++-- common/utils/file.h | 67 +- common/utils/filedialog.cpp | 119 +- common/utils/filedialog.h | 15 +- common/utils/fontdialog.h | 10 +- common/utils/globallocale.cpp | 7 +- common/utils/globallocale.h | 6 +- common/utils/icon.h | 20 +- common/utils/lineedit.cpp | 83 +- common/utils/lineedit.h | 30 +- common/utils/messagebox.cpp | 74 +- common/utils/messagebox.h | 18 +- common/utils/pagedialog.cpp | 210 ++-- common/utils/pagedialog.h | 36 +- common/utils/printpreviewdialog.cpp | 100 +- common/utils/printpreviewdialog.h | 24 +- common/utils/recentfilesaction.cpp | 166 ++- common/utils/recentfilesaction.h | 54 +- common/utils/selectaction.cpp | 94 +- common/utils/selectaction.h | 44 +- common/utils/standardaction.cpp | 407 +++---- common/utils/standardaction.h | 5 +- common/utils/tempdir.cpp | 42 +- common/utils/tempdir.h | 6 +- common/utils/toggleaction.cpp | 46 +- common/utils/toggleaction.h | 26 +- common/utils/toolbar.cpp | 53 +- common/utils/toolbar.h | 16 +- common/utils/url.cpp | 24 +- common/utils/url.h | 10 +- common/utils/urlcompletion.h | 25 +- common/utils/zoomaction.cpp | 151 ++- common/utils/zoomaction.h | 25 +- part/browserextension.cpp | 23 +- part/browserextension.h | 13 +- part/configdialog.cpp | 120 +- part/configdialog.h | 27 +- part/configgeneralwidget.cpp | 78 +- part/configgeneralwidget.h | 19 +- part/part.cpp | 381 +++--- part/part.h | 60 +- 116 files changed, 7807 insertions(+), 7705 deletions(-) diff --git a/app/aboutdialog.cpp b/app/aboutdialog.cpp index 88ca0f5..9d2d787 100644 --- a/app/aboutdialog.cpp +++ b/app/aboutdialog.cpp @@ -25,45 +25,48 @@ #include "ktikzapplication.h" -AboutDialog::AboutDialog(QWidget *parent) - : QDialog(parent) +AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) { - QLabel *pixmapLabel = new QLabel; - pixmapLabel->setPixmap(QPixmap(QLatin1String(":/icons/qtikz-128.png"))); - QLabel *label = new QLabel(QString(QLatin1String("

%1 %2

%3

%4

")) - .arg(KtikzApplication::applicationName()) - .arg(QCoreApplication::applicationVersion()) - .arg(tr("Copyright 2007-2014 Florian Hackenberger and Glad Deschrijver")) - .arg(tr("This is a program for creating TikZ (from the LaTeX pgf package) diagrams."))); - label->setWordWrap(true); + QLabel *pixmapLabel = new QLabel; + pixmapLabel->setPixmap(QPixmap(QLatin1String(":/icons/qtikz-128.png"))); + QLabel *label = new QLabel( + QString(QLatin1String("

%1 %2

%3

%4

")) + .arg(KtikzApplication::applicationName()) + .arg(QCoreApplication::applicationVersion()) + .arg(tr("Copyright 2007-2014 Florian Hackenberger and Glad Deschrijver")) + .arg(tr("This is a program for creating TikZ (from the LaTeX pgf package) " + "diagrams."))); + label->setWordWrap(true); - QWidget *topWidget = new QWidget; - QHBoxLayout *topLayout = new QHBoxLayout; - topLayout->addWidget(pixmapLabel); - topLayout->addWidget(label); - topWidget->setLayout(topLayout); + QWidget *topWidget = new QWidget; + QHBoxLayout *topLayout = new QHBoxLayout; + topLayout->addWidget(pixmapLabel); + topLayout->addWidget(label); + topWidget->setLayout(topLayout); - QTextBrowser *textEdit = new QTextBrowser; - textEdit->setHtml(tr("

This program is free " - "software; you can redistribute it and/or modify it under the " - "terms of the GNU General Public License as published by the " - "Free Software Foundation; either version 2 of the License, " - "or (at your option) any later version.

" - "

This program is distributed in the hope that it will " - "be useful, but WITHOUT ANY WARRANTY; without even the implied " - "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. " - "See the GNU General Public License for more details.

")); - textEdit->setReadOnly(true); - textEdit->setOpenExternalLinks(true); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + QTextBrowser *textEdit = new QTextBrowser; + textEdit->setHtml( + tr("

This program is free " + "software; you can redistribute it and/or modify it under the " + "terms of the GNU General Public License as published by the " + "Free Software Foundation; either version 2 of the License, " + "or (at your option) any later version.

" + "

This program is distributed in the hope that it will " + "be useful, but WITHOUT ANY WARRANTY; without even the implied " + "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. " + "See the GNU " + "General Public License for more details.

")); + textEdit->setReadOnly(true); + textEdit->setOpenExternalLinks(true); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->addWidget(topWidget); - mainLayout->addWidget(textEdit); - mainLayout->addWidget(buttonBox); - mainLayout->setSpacing(10); - buttonBox->setFocus(); + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->addWidget(topWidget); + mainLayout->addWidget(textEdit); + mainLayout->addWidget(buttonBox); + mainLayout->setSpacing(10); + buttonBox->setFocus(); - setWindowTitle(tr("About %1").arg(KtikzApplication::applicationName())); + setWindowTitle(tr("About %1").arg(KtikzApplication::applicationName())); } diff --git a/app/aboutdialog.h b/app/aboutdialog.h index 9ab5735..f106e7a 100644 --- a/app/aboutdialog.h +++ b/app/aboutdialog.h @@ -24,10 +24,10 @@ class AboutDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit AboutDialog(QWidget *parent = 0); + explicit AboutDialog(QWidget *parent = 0); }; #endif diff --git a/app/assistantcontroller.cpp b/app/assistantcontroller.cpp index ed4a80c..62b197c 100644 --- a/app/assistantcontroller.cpp +++ b/app/assistantcontroller.cpp @@ -26,69 +26,65 @@ #include "ktikzapplication.h" -AssistantController::AssistantController() - : m_process(0) -{ -} +AssistantController::AssistantController() : m_process(0) { } AssistantController::~AssistantController() { - if (m_process && m_process->state() == QProcess::Running) - { - m_process->terminate(); - m_process->waitForFinished(3000); - } - delete m_process; + if (m_process && m_process->state() == QProcess::Running) { + m_process->terminate(); + m_process->waitForFinished(3000); + } + delete m_process; } bool AssistantController::startAssistant() { - if (!m_process) - m_process = new QProcess(); + if (!m_process) + m_process = new QProcess(); - if (m_process->state() != QProcess::Running) - { - QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator(); + if (m_process->state() != QProcess::Running) { + QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator(); #if !defined(Q_OS_MAC) - app += QLatin1String("assistant"); + app += QLatin1String("assistant"); #else - app += QLatin1String("Assistant.app/Contents/MacOS/Assistant"); + app += QLatin1String("Assistant.app/Contents/MacOS/Assistant"); #endif - const QString ktikzDocFile = QString::fromLocal8Bit(KTIKZ_DOCUMENTATION_INSTALL_DIR) + QLatin1String("/qtikz.qhc"); - if (!QFileInfo(ktikzDocFile).isReadable()) - { - QMessageBox::critical(0, KtikzApplication::applicationName(), - QCoreApplication::translate("AssistantController", "Unable to open the help file (%1)").arg(ktikzDocFile)); - return false; - } + const QString ktikzDocFile = QString::fromLocal8Bit(KTIKZ_DOCUMENTATION_INSTALL_DIR) + + QLatin1String("/qtikz.qhc"); + if (!QFileInfo(ktikzDocFile).isReadable()) { + QMessageBox::critical(0, KtikzApplication::applicationName(), + QCoreApplication::translate("AssistantController", + "Unable to open the help file (%1)") + .arg(ktikzDocFile)); + return false; + } - QStringList args; - args << QLatin1String("-collectionFile") - << ktikzDocFile - << QLatin1String("-enableRemoteControl"); + QStringList args; + args << QLatin1String("-collectionFile") << ktikzDocFile + << QLatin1String("-enableRemoteControl"); - m_process->start(app, args); + m_process->start(app, args); - if (!m_process->waitForStarted()) - { - QMessageBox::critical(0, KtikzApplication::applicationName(), - QCoreApplication::translate("AssistantController", "Unable to launch Qt Assistant (%1)").arg(app)); - return false; - } - } - return true; + if (!m_process->waitForStarted()) { + QMessageBox::critical(0, KtikzApplication::applicationName(), + QCoreApplication::translate("AssistantController", + "Unable to launch Qt Assistant (%1)") + .arg(app)); + return false; + } + } + return true; } void AssistantController::showDocumentation(const QString &page) { - if (!startAssistant()) - return; + if (!startAssistant()) + return; - if (!page.isEmpty()) - { - QByteArray ba; - ba.append("setSource qthelp://hackenberger.qtikz/doc/"); - m_process->write(ba + page.toLocal8Bit() + '\0'); - } + if (!page.isEmpty()) { + QByteArray ba; + ba.append("setSource qthelp://hackenberger.qtikz/doc/"); + m_process->write(ba + page.toLocal8Bit() + '\0'); + } } diff --git a/app/assistantcontroller.h b/app/assistantcontroller.h index d4113bc..f5c6e40 100644 --- a/app/assistantcontroller.h +++ b/app/assistantcontroller.h @@ -26,15 +26,15 @@ class QProcess; class AssistantController { public: - AssistantController(); - ~AssistantController(); + AssistantController(); + ~AssistantController(); - void showDocumentation(const QString &page = QString()); + void showDocumentation(const QString &page = QString()); private: - bool startAssistant(); + bool startAssistant(); - QProcess *m_process; + QProcess *m_process; }; #endif diff --git a/app/configappearancewidget.cpp b/app/configappearancewidget.cpp index c2958cd..50fa0d5 100644 --- a/app/configappearancewidget.cpp +++ b/app/configappearancewidget.cpp @@ -26,273 +26,274 @@ #include "../common/utils/colordialog.h" #include "../common/utils/fontdialog.h" -ConfigAppearanceWidget::ConfigAppearanceWidget(QWidget *parent) - : QWidget(parent) +ConfigAppearanceWidget::ConfigAppearanceWidget(QWidget *parent) : QWidget(parent) { - m_itemMargin = 10; - - ui.setupUi(this); - - QButtonGroup *buttonGroup = new QButtonGroup(this); - buttonGroup->addButton(ui.standardAppearanceCheck); - buttonGroup->addButton(ui.customAppearanceCheck); - buttonGroup->setExclusive(true); - connect(buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(toggleCustom())); - - QPalette palette = ui.itemTable->palette(); - QColor highlightBackgroundColor(QApplication::style()->standardPalette().color(QPalette::Normal, QPalette::AlternateBase)); - if (highlightBackgroundColor == QApplication::style()->standardPalette().color(QPalette::Normal, QPalette::Base)) - highlightBackgroundColor = highlightBackgroundColor.darker(110); - palette.setColor(QPalette::Normal, QPalette::Highlight, highlightBackgroundColor); - palette.setColor(QPalette::Normal, QPalette::HighlightedText, QPalette::Text); - palette.setColor(QPalette::Inactive, QPalette::Highlight, highlightBackgroundColor); - palette.setColor(QPalette::Inactive, QPalette::HighlightedText, QPalette::Text); - palette.setColor(QPalette::Disabled, QPalette::Highlight, highlightBackgroundColor); - ui.itemTable->setPalette(palette); - m_itemHighlighted = -1; - connect(ui.itemTable, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), this, SLOT(setItemHighlighted(QTableWidgetItem*))); - - connect(ui.fontButton, SIGNAL(clicked()), this, SLOT(showFontDialog())); - connect(ui.colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog())); + m_itemMargin = 10; + + ui.setupUi(this); + + QButtonGroup *buttonGroup = new QButtonGroup(this); + buttonGroup->addButton(ui.standardAppearanceCheck); + buttonGroup->addButton(ui.customAppearanceCheck); + buttonGroup->setExclusive(true); + connect(buttonGroup, SIGNAL(buttonClicked(QAbstractButton *)), this, SLOT(toggleCustom())); + + QPalette palette = ui.itemTable->palette(); + QColor highlightBackgroundColor(QApplication::style()->standardPalette().color( + QPalette::Normal, QPalette::AlternateBase)); + if (highlightBackgroundColor + == QApplication::style()->standardPalette().color(QPalette::Normal, QPalette::Base)) + highlightBackgroundColor = highlightBackgroundColor.darker(110); + palette.setColor(QPalette::Normal, QPalette::Highlight, highlightBackgroundColor); + palette.setColor(QPalette::Normal, QPalette::HighlightedText, QPalette::Text); + palette.setColor(QPalette::Inactive, QPalette::Highlight, highlightBackgroundColor); + palette.setColor(QPalette::Inactive, QPalette::HighlightedText, QPalette::Text); + palette.setColor(QPalette::Disabled, QPalette::Highlight, highlightBackgroundColor); + ui.itemTable->setPalette(palette); + m_itemHighlighted = -1; + connect(ui.itemTable, SIGNAL(currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)), this, + SLOT(setItemHighlighted(QTableWidgetItem *))); + + connect(ui.fontButton, SIGNAL(clicked()), this, SLOT(showFontDialog())); + connect(ui.colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog())); } void ConfigAppearanceWidget::readSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); - m_custom = settings.value(QLatin1String("Customize"), true).toBool(); - const int numOfRules = settings.value(QLatin1String("Number"), 0).toInt(); - for (int i = 0; i < numOfRules; ++i) - { - const int num = m_typeNames.indexOf(settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Name")).toString()); - if (num >= 0) - { - m_itemColors[num] = settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Color")).toString(); - m_itemFonts[num] = settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Font")).toString(); - } - } - settings.endGroup(); - - setCustomizationType(m_custom); - setItemFonts(m_itemFonts); - setItemColors(m_itemColors); + QSettings settings; + settings.beginGroup(settingsGroup); + m_custom = settings.value(QLatin1String("Customize"), true).toBool(); + const int numOfRules = settings.value(QLatin1String("Number"), 0).toInt(); + for (int i = 0; i < numOfRules; ++i) { + const int num = m_typeNames.indexOf( + settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Name")) + .toString()); + if (num >= 0) { + m_itemColors[num] = settings.value(QLatin1String("Item") + QString::number(i) + + QLatin1String("/Color")) + .toString(); + m_itemFonts[num] = settings.value(QLatin1String("Item") + QString::number(i) + + QLatin1String("/Font")) + .toString(); + } + } + settings.endGroup(); + + setCustomizationType(m_custom); + setItemFonts(m_itemFonts); + setItemColors(m_itemColors); } void ConfigAppearanceWidget::writeSettings(const QString &settingsGroup) { - m_custom = getCustomizationType(); - - QSettings settings; - settings.beginGroup(settingsGroup); - settings.setValue(QLatin1String("Customize"), m_custom); - if (m_custom) - { - for (int i = 0; i < m_typeNames.size(); ++i) - { - settings.setValue(QLatin1String("Item") + QString::number(i) + QLatin1String("/Name"), m_typeNames.at(i)); - settings.setValue(QLatin1String("Item") + QString::number(i) + QLatin1String("/Color"), m_itemColors.at(i)); - settings.setValue(QLatin1String("Item") + QString::number(i) + QLatin1String("/Font"), m_itemFonts.at(i)); - } - settings.setValue(QLatin1String("Number"), m_typeNames.size()); - } - settings.endGroup(); + m_custom = getCustomizationType(); + + QSettings settings; + settings.beginGroup(settingsGroup); + settings.setValue(QLatin1String("Customize"), m_custom); + if (m_custom) { + for (int i = 0; i < m_typeNames.size(); ++i) { + settings.setValue(QLatin1String("Item") + QString::number(i) + QLatin1String("/Name"), + m_typeNames.at(i)); + settings.setValue(QLatin1String("Item") + QString::number(i) + QLatin1String("/Color"), + m_itemColors.at(i)); + settings.setValue(QLatin1String("Item") + QString::number(i) + QLatin1String("/Font"), + m_itemFonts.at(i)); + } + settings.setValue(QLatin1String("Number"), m_typeNames.size()); + } + settings.endGroup(); } void ConfigAppearanceWidget::setItemHighlighted(QTableWidgetItem *item) { - m_itemHighlighted = ui.itemTable->row(item); - setHighlightedForeground(m_itemColors.at(m_itemHighlighted)); - ui.fontButton->setEnabled(true); - ui.colorButton->setEnabled(true); + m_itemHighlighted = ui.itemTable->row(item); + setHighlightedForeground(m_itemColors.at(m_itemHighlighted)); + ui.fontButton->setEnabled(true); + ui.colorButton->setEnabled(true); } void ConfigAppearanceWidget::setItemToolTip(QTableWidgetItem *item, const QFont &font) { - const QFontMetrics metrics(font); - ui.itemTable->setRowHeight(m_itemHighlighted, metrics.height() + m_itemMargin); - if (metrics.width(item->text()) >= ui.itemTable->contentsRect().width() - 30) - item->setToolTip(item->text()); - else - item->setToolTip(QString()); + const QFontMetrics metrics(font); + ui.itemTable->setRowHeight(m_itemHighlighted, metrics.height() + m_itemMargin); + if (metrics.width(item->text()) >= ui.itemTable->contentsRect().width() - 30) + item->setToolTip(item->text()); + else + item->setToolTip(QString()); } -void ConfigAppearanceWidget::showEvent(QShowEvent*) +void ConfigAppearanceWidget::showEvent(QShowEvent *) { - for (int i = 0; i < ui.itemTable->rowCount(); ++i) - { - QFont font; - font.fromString(m_itemFonts.at(i)); - setItemToolTip(ui.itemTable->item(i, 0), font); - } - - if (m_itemHighlighted < 0) - return; - setHighlightedForeground(m_itemColors.at(m_itemHighlighted)); + for (int i = 0; i < ui.itemTable->rowCount(); ++i) { + QFont font; + font.fromString(m_itemFonts.at(i)); + setItemToolTip(ui.itemTable->item(i, 0), font); + } + + if (m_itemHighlighted < 0) + return; + setHighlightedForeground(m_itemColors.at(m_itemHighlighted)); } void ConfigAppearanceWidget::addItem(const QString &titleName) { - const int itemTableRowNum = ui.itemTable->rowCount(); - ui.itemTable->setRowCount(itemTableRowNum + 1); - - QTableWidgetItem *item = new QTableWidgetItem; - item->setText(titleName); - item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); - item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - ui.itemTable->setItem(itemTableRowNum, 0, item); + const int itemTableRowNum = ui.itemTable->rowCount(); + ui.itemTable->setRowCount(itemTableRowNum + 1); + + QTableWidgetItem *item = new QTableWidgetItem; + item->setText(titleName); + item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + ui.itemTable->setItem(itemTableRowNum, 0, item); } void ConfigAppearanceWidget::addItemFont(const QString &fontName) { - const int rowNum = m_itemFonts.size(); - m_itemFonts.append(fontName); + const int rowNum = m_itemFonts.size(); + m_itemFonts.append(fontName); - QFont font; - font.fromString(fontName); - ui.itemTable->item(rowNum, 0)->setFont(font); - ui.itemTable->setRowHeight(rowNum, QFontMetrics(font).height() + m_itemMargin); + QFont font; + font.fromString(fontName); + ui.itemTable->item(rowNum, 0)->setFont(font); + ui.itemTable->setRowHeight(rowNum, QFontMetrics(font).height() + m_itemMargin); } void ConfigAppearanceWidget::addItemColor(const QString &colorName) { - const int rowNum = m_itemColors.size(); - m_itemColors.append(colorName); - ui.itemTable->item(rowNum, 0)->setForeground(QColor(colorName)); - toggleCustom(); + const int rowNum = m_itemColors.size(); + m_itemColors.append(colorName); + ui.itemTable->item(rowNum, 0)->setForeground(QColor(colorName)); + toggleCustom(); } void ConfigAppearanceWidget::addItems(const QStringList &titleNames) { - for (int i = 0; i < titleNames.size(); ++i) - addItem(titleNames.at(i)); + for (int i = 0; i < titleNames.size(); ++i) + addItem(titleNames.at(i)); } void ConfigAppearanceWidget::setItemFonts(const QStringList &fontNames) { - m_itemFonts = fontNames; - for (int i = 0; i < m_itemFonts.size(); ++i) - { - QFont font; - font.fromString(m_itemFonts.at(i)); - ui.itemTable->item(i, 0)->setFont(font); - ui.itemTable->setRowHeight(i, QFontMetrics(font).height() + m_itemMargin); - } + m_itemFonts = fontNames; + for (int i = 0; i < m_itemFonts.size(); ++i) { + QFont font; + font.fromString(m_itemFonts.at(i)); + ui.itemTable->item(i, 0)->setFont(font); + ui.itemTable->setRowHeight(i, QFontMetrics(font).height() + m_itemMargin); + } } void ConfigAppearanceWidget::setItemColors(const QStringList &colorNames) { - m_itemColors = colorNames; - for (int i = 0; i < m_itemColors.size(); ++i) - ui.itemTable->item(i, 0)->setForeground(QColor(m_itemColors.at(i))); - toggleCustom(); + m_itemColors = colorNames; + for (int i = 0; i < m_itemColors.size(); ++i) + ui.itemTable->item(i, 0)->setForeground(QColor(m_itemColors.at(i))); + toggleCustom(); } QStringList ConfigAppearanceWidget::getItemFonts() { - return m_itemFonts; + return m_itemFonts; } QStringList ConfigAppearanceWidget::getItemColors() { - return m_itemColors; + return m_itemColors; } void ConfigAppearanceWidget::setCustomizationType(bool custom) { - if (custom) - ui.customAppearanceCheck->setChecked(true); - else - ui.standardAppearanceCheck->setChecked(true); - toggleCustom(); + if (custom) + ui.customAppearanceCheck->setChecked(true); + else + ui.standardAppearanceCheck->setChecked(true); + toggleCustom(); } bool ConfigAppearanceWidget::getCustomizationType() { - return !ui.standardAppearanceCheck->isChecked(); + return !ui.standardAppearanceCheck->isChecked(); } void ConfigAppearanceWidget::toggleCustom() { - if (ui.customAppearanceCheck->isChecked()) - { - ui.appearanceGroupBox->setEnabled(true); - for (int i = 0; i < m_itemColors.size(); ++i) - ui.itemTable->item(i, 0)->setForeground(QColor(m_itemColors.at(i))); - } - else - { - ui.appearanceGroupBox->setEnabled(false); - for (int i = 0; i < m_itemColors.size(); ++i) - ui.itemTable->item(i, 0)->setForeground(QApplication::style()->standardPalette().color(QPalette::Disabled, QPalette::Text)); - } + if (ui.customAppearanceCheck->isChecked()) { + ui.appearanceGroupBox->setEnabled(true); + for (int i = 0; i < m_itemColors.size(); ++i) + ui.itemTable->item(i, 0)->setForeground(QColor(m_itemColors.at(i))); + } else { + ui.appearanceGroupBox->setEnabled(false); + for (int i = 0; i < m_itemColors.size(); ++i) + ui.itemTable->item(i, 0)->setForeground(QApplication::style()->standardPalette().color( + QPalette::Disabled, QPalette::Text)); + } } void ConfigAppearanceWidget::setTypeNames(const QStringList &typeNames) { - m_typeNames = typeNames; + m_typeNames = typeNames; } -void ConfigAppearanceWidget::setDefaultTextCharFormats(const QMap &defaultFormatList) +void ConfigAppearanceWidget::setDefaultTextCharFormats( + const QMap &defaultFormatList) { - for (int i = 0; i < defaultFormatList.size(); ++i) - { - m_itemColors << QString(); - m_itemFonts << QString(); - } - - QMap::const_iterator it = defaultFormatList.constBegin(); - while (it != defaultFormatList.constEnd()) - { - const int num = m_typeNames.indexOf(it.key()); - if (num >= 0) - { - m_itemColors[num] = it.value().foreground().color().name(); - m_itemFonts[num] = it.value().font().toString(); - } - ++it; - } + for (int i = 0; i < defaultFormatList.size(); ++i) { + m_itemColors << QString(); + m_itemFonts << QString(); + } + + QMap::const_iterator it = defaultFormatList.constBegin(); + while (it != defaultFormatList.constEnd()) { + const int num = m_typeNames.indexOf(it.key()); + if (num >= 0) { + m_itemColors[num] = it.value().foreground().color().name(); + m_itemFonts[num] = it.value().font().toString(); + } + ++it; + } } void ConfigAppearanceWidget::showFontDialog() { - if (m_itemHighlighted < 0) - return; - - bool ok; - QFont currentFont; - currentFont.fromString(m_itemFonts.at(m_itemHighlighted)); - const QFont newFont = FontDialog::getFont(&ok, currentFont, this); - if (ok) - { - QTableWidgetItem *item = ui.itemTable->item(m_itemHighlighted, 0); - m_itemFonts.replace(m_itemHighlighted, newFont.toString()); - item->setFont(newFont); - setItemToolTip(item, newFont); - } + if (m_itemHighlighted < 0) + return; + + bool ok; + QFont currentFont; + currentFont.fromString(m_itemFonts.at(m_itemHighlighted)); + const QFont newFont = FontDialog::getFont(&ok, currentFont, this); + if (ok) { + QTableWidgetItem *item = ui.itemTable->item(m_itemHighlighted, 0); + m_itemFonts.replace(m_itemHighlighted, newFont.toString()); + item->setFont(newFont); + setItemToolTip(item, newFont); + } } void ConfigAppearanceWidget::showColorDialog() { - if (m_itemHighlighted < 0) - return; - - bool ok; - const QColor currentColor(m_itemColors.at(m_itemHighlighted)); - const QColor newColor = ColorDialog::getColor(&ok, currentColor, this); - if (ok) - { - m_itemColors.replace(m_itemHighlighted, newColor.name()); - ui.itemTable->item(m_itemHighlighted, 0)->setForeground(newColor); - setHighlightedForeground(m_itemColors.at(m_itemHighlighted)); - } + if (m_itemHighlighted < 0) + return; + + bool ok; + const QColor currentColor(m_itemColors.at(m_itemHighlighted)); + const QColor newColor = ColorDialog::getColor(&ok, currentColor, this); + if (ok) { + m_itemColors.replace(m_itemHighlighted, newColor.name()); + ui.itemTable->item(m_itemHighlighted, 0)->setForeground(newColor); + setHighlightedForeground(m_itemColors.at(m_itemHighlighted)); + } } void ConfigAppearanceWidget::setHighlightedForeground(const QString &colorName) { - QPalette palette = ui.itemTable->palette(); - const QColor color(colorName); - palette.setColor(QPalette::Normal, QPalette::HighlightedText, color); - palette.setColor(QPalette::Inactive, QPalette::HighlightedText, color); - palette.setColor(QPalette::Disabled, QPalette::HighlightedText, QApplication::style()->standardPalette().color(QPalette::Disabled, QPalette::Text)); - ui.itemTable->setPalette(palette); + QPalette palette = ui.itemTable->palette(); + const QColor color(colorName); + palette.setColor(QPalette::Normal, QPalette::HighlightedText, color); + palette.setColor(QPalette::Inactive, QPalette::HighlightedText, color); + palette.setColor( + QPalette::Disabled, QPalette::HighlightedText, + QApplication::style()->standardPalette().color(QPalette::Disabled, QPalette::Text)); + ui.itemTable->setPalette(palette); } diff --git a/app/configappearancewidget.h b/app/configappearancewidget.h index 8754936..7bf7dec 100644 --- a/app/configappearancewidget.h +++ b/app/configappearancewidget.h @@ -28,47 +28,47 @@ class QTextCharFormat; class ConfigAppearanceWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ConfigAppearanceWidget(QWidget *parent = 0); + explicit ConfigAppearanceWidget(QWidget *parent = 0); - void readSettings(const QString &settingsGroup); - void writeSettings(const QString &settingsGroup); + void readSettings(const QString &settingsGroup); + void writeSettings(const QString &settingsGroup); - void addItem(const QString &titleName); - void addItemFont(const QString &fontName); - void addItemColor(const QString &colorName); - void addItems(const QStringList &titleNames); - void setItemFonts(const QStringList &fontNames); - void setItemColors(const QStringList &colorNames); - void setCustomizationType(bool custom); - QStringList getItemFonts(); - QStringList getItemColors(); - bool getCustomizationType(); - void setTypeNames(const QStringList &typeNames); - void setDefaultTextCharFormats(const QMap &defaultFormatList); + void addItem(const QString &titleName); + void addItemFont(const QString &fontName); + void addItemColor(const QString &colorName); + void addItems(const QStringList &titleNames); + void setItemFonts(const QStringList &fontNames); + void setItemColors(const QStringList &colorNames); + void setCustomizationType(bool custom); + QStringList getItemFonts(); + QStringList getItemColors(); + bool getCustomizationType(); + void setTypeNames(const QStringList &typeNames); + void setDefaultTextCharFormats(const QMap &defaultFormatList); protected: - Ui::ConfigAppearanceWidget ui; + Ui::ConfigAppearanceWidget ui; private Q_SLOTS: - void setItemHighlighted(QTableWidgetItem *item); - void toggleCustom(); - void showFontDialog(); - void showColorDialog(); + void setItemHighlighted(QTableWidgetItem *item); + void toggleCustom(); + void showFontDialog(); + void showColorDialog(); private: - void showEvent(QShowEvent*); - void setHighlightedForeground(const QString &colorName); - void setItemToolTip(QTableWidgetItem *item, const QFont &font); + void showEvent(QShowEvent *); + void setHighlightedForeground(const QString &colorName); + void setItemToolTip(QTableWidgetItem *item, const QFont &font); - int m_itemHighlighted; - int m_itemMargin; - bool m_custom; - QStringList m_itemFonts; - QStringList m_itemColors; - QStringList m_typeNames; + int m_itemHighlighted; + int m_itemMargin; + bool m_custom; + QStringList m_itemFonts; + QStringList m_itemColors; + QStringList m_typeNames; }; #endif diff --git a/app/configdialog.cpp b/app/configdialog.cpp index 13d0a6c..dc2974c 100644 --- a/app/configdialog.cpp +++ b/app/configdialog.cpp @@ -31,84 +31,82 @@ ConfigDialog::ConfigDialog(QWidget *parent) : PageDialog(parent) { - setWindowTitle(tr("Configure %1").arg(KtikzApplication::applicationName())); -// TODO: Check if this is needed -// setHelp(QLatin1String("chap-configuration")); + setWindowTitle(tr("Configure %1").arg(KtikzApplication::applicationName())); + // TODO: Check if this is needed + // setHelp(QLatin1String("chap-configuration")); - - - m_configGeneralWidget = new ConfigGeneralWidget(this); - addPage(m_configGeneralWidget, tr("&General"), QLatin1String("preferences-desktop-theme")); + m_configGeneralWidget = new ConfigGeneralWidget(this); + addPage(m_configGeneralWidget, tr("&General"), QLatin1String("preferences-desktop-theme")); #ifdef KTIKZ_USE_KTEXTEDITOR - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - bool showEditorConfig = settings.value(QLatin1String("EditorWidget"), 0).toInt() == 0; - if (!showEditorConfig) - { - m_configEditorWidget = NULL; - } - else + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + bool showEditorConfig = settings.value(QLatin1String("EditorWidget"), 0).toInt() == 0; + if (!showEditorConfig) { + m_configEditorWidget = NULL; + } else #endif - { - m_configEditorWidget = new ConfigEditorWidget(this); - addPage(m_configEditorWidget, tr("&Editor"), QLatin1String("accessories-text-editor")); - } - - m_configAppearanceWidget = new ConfigAppearanceWidget(this); - addPage(m_configAppearanceWidget, tr("&Highlighting"), QLatin1String("preferences-desktop-color")); + { + m_configEditorWidget = new ConfigEditorWidget(this); + addPage(m_configEditorWidget, tr("&Editor"), QLatin1String("accessories-text-editor")); + } + + m_configAppearanceWidget = new ConfigAppearanceWidget(this); + addPage(m_configAppearanceWidget, tr("&Highlighting"), + QLatin1String("preferences-desktop-color")); - m_configPreviewWidget = new ConfigPreviewWidget(this); - addPage(m_configPreviewWidget, tr("&Preview"), QLatin1String("preferences-desktop-theme")); + m_configPreviewWidget = new ConfigPreviewWidget(this); + addPage(m_configPreviewWidget, tr("&Preview"), QLatin1String("preferences-desktop-theme")); } void ConfigDialog::readSettings() { - m_configGeneralWidget->readSettings(QString()); + m_configGeneralWidget->readSettings(QString()); #ifdef KTIKZ_USE_KTEXTEDITOR - if( m_configEditorWidget) + if (m_configEditorWidget) #endif - m_configEditorWidget->readSettings(QLatin1String("Editor")); - m_configAppearanceWidget->readSettings(QLatin1String("Highlighting")); - m_configPreviewWidget->readSettings(QLatin1String("Preview")); + m_configEditorWidget->readSettings(QLatin1String("Editor")); + m_configAppearanceWidget->readSettings(QLatin1String("Highlighting")); + m_configPreviewWidget->readSettings(QLatin1String("Preview")); } void ConfigDialog::writeSettings() { - m_configGeneralWidget->writeSettings(QString()); + m_configGeneralWidget->writeSettings(QString()); #ifdef KTIKZ_USE_KTEXTEDITOR - if( m_configEditorWidget) + if (m_configEditorWidget) #endif - m_configEditorWidget->writeSettings(QLatin1String("Editor")); - m_configAppearanceWidget->writeSettings(QLatin1String("Highlighting")); - m_configPreviewWidget->writeSettings(QLatin1String("Preview")); + m_configEditorWidget->writeSettings(QLatin1String("Editor")); + m_configAppearanceWidget->writeSettings(QLatin1String("Highlighting")); + m_configPreviewWidget->writeSettings(QLatin1String("Preview")); } void ConfigDialog::setTranslatedHighlightTypeNames(const QStringList &typeNames) { - Q_FOREACH (const QString &typeName, typeNames) - m_configAppearanceWidget->addItem(typeName); + Q_FOREACH (const QString &typeName, typeNames) + m_configAppearanceWidget->addItem(typeName); } void ConfigDialog::setHighlightTypeNames(const QStringList &typeNames) { - m_configAppearanceWidget->setTypeNames(typeNames); + m_configAppearanceWidget->setTypeNames(typeNames); } -void ConfigDialog::setDefaultHighlightFormats(const QMap &defaultFormatList) +void ConfigDialog::setDefaultHighlightFormats( + const QMap &defaultFormatList) { - m_configAppearanceWidget->setDefaultTextCharFormats(defaultFormatList); + m_configAppearanceWidget->setDefaultTextCharFormats(defaultFormatList); } void ConfigDialog::accept() { - writeSettings(); - Q_EMIT settingsChanged(); - QDialog::accept(); + writeSettings(); + Q_EMIT settingsChanged(); + QDialog::accept(); } void ConfigDialog::keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_F1 && event->modifiers() == Qt::ShiftModifier) - QWhatsThis::enterWhatsThisMode(); - QDialog::keyPressEvent(event); + if (event->key() == Qt::Key_F1 && event->modifiers() == Qt::ShiftModifier) + QWhatsThis::enterWhatsThisMode(); + QDialog::keyPressEvent(event); } diff --git a/app/configdialog.h b/app/configdialog.h index bb9cba7..b4875d1 100644 --- a/app/configdialog.h +++ b/app/configdialog.h @@ -30,31 +30,31 @@ class ConfigPreviewWidget; class ConfigDialog : public PageDialog { - Q_OBJECT + Q_OBJECT public: - explicit ConfigDialog(QWidget *parent = 0); + explicit ConfigDialog(QWidget *parent = 0); - void readSettings(); - void writeSettings(); + void readSettings(); + void writeSettings(); - void setTranslatedHighlightTypeNames(const QStringList &typeNames); - void setHighlightTypeNames(const QStringList &typeNames); - void setDefaultHighlightFormats(const QMap &defaultFormatList); + void setTranslatedHighlightTypeNames(const QStringList &typeNames); + void setHighlightTypeNames(const QStringList &typeNames); + void setDefaultHighlightFormats(const QMap &defaultFormatList); Q_SIGNALS: - void settingsChanged(); + void settingsChanged(); private Q_SLOTS: - void accept(); + void accept(); private: - void keyPressEvent(QKeyEvent *event); + void keyPressEvent(QKeyEvent *event); - ConfigAppearanceWidget *m_configAppearanceWidget; - ConfigEditorWidget *m_configEditorWidget; - ConfigGeneralWidget *m_configGeneralWidget; - ConfigPreviewWidget *m_configPreviewWidget; + ConfigAppearanceWidget *m_configAppearanceWidget; + ConfigEditorWidget *m_configEditorWidget; + ConfigGeneralWidget *m_configGeneralWidget; + ConfigPreviewWidget *m_configPreviewWidget; }; #endif diff --git a/app/configeditorwidget.cpp b/app/configeditorwidget.cpp index 77a73dd..ce9b39a 100644 --- a/app/configeditorwidget.cpp +++ b/app/configeditorwidget.cpp @@ -27,237 +27,259 @@ #include "../common/utils/fontdialog.h" -ConfigEditorWidget::ConfigEditorWidget(QWidget *parent) - : QWidget(parent) +ConfigEditorWidget::ConfigEditorWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); + ui.setupUi(this); - connect(ui.generalFontButton, SIGNAL(clicked()), this, SLOT(selectFont())); + connect(ui.generalFontButton, SIGNAL(clicked()), this, SLOT(selectFont())); - // ** Encoding - initializeEncoding(); + // ** Encoding + initializeEncoding(); } void ConfigEditorWidget::initializeEncoding() { - /// Local codec - QTextCodec* localCodec = QTextCodec::codecForLocale(); - QString localCodecName; - if (localCodec->aliases().empty()) - localCodecName = codecNameToString( localCodec); - else - localCodecName = codecNameToString( localCodec->aliases()[1]); - - ui.encodingComboBox->addItem(tr("System local - %1", "Encoding").arg(localCodecName), QString::fromLatin1("System")); - ui.encodingComboBox->addItem(tr("UTF-8", "Encoding"), QString::fromLatin1("UTF-8 BOM")); - ui.encodingComboBox->addItem(tr("UTF-8 without BOM", "Encoding"), QString::fromLatin1("UTF-8")); - ui.encodingComboBox->addItem(tr("(Advanced)", "Encoding"), QString()); - ui.encodingComboBox->setCurrentIndex(ui.encodingComboBox->count()-1); - - - - QComboBox* cb (ui.defaultEncodingComboBox); - cb->addItem(tr("(Local codec - %1)", "Encoding").arg(localCodecName), QVariant() - ); - fillCodecComboBox(cb); - - - cb = ui.readEncodingComboBox; - cb->addItem(tr("(Local or unicode)", "Encoding"), QVariant()); - fillCodecComboBox(cb); - - cb = ui.writeEncodingComboBox; - cb->addItem(tr("(Same)", "Encoding"), QVariant()); - fillCodecComboBox(cb); + /// Local codec + QTextCodec *localCodec = QTextCodec::codecForLocale(); + QString localCodecName; + if (localCodec->aliases().empty()) + localCodecName = codecNameToString(localCodec); + else + localCodecName = codecNameToString(localCodec->aliases()[1]); + + ui.encodingComboBox->addItem(tr("System local - %1", "Encoding").arg(localCodecName), + QString::fromLatin1("System")); + ui.encodingComboBox->addItem(tr("UTF-8", "Encoding"), QString::fromLatin1("UTF-8 BOM")); + ui.encodingComboBox->addItem(tr("UTF-8 without BOM", "Encoding"), QString::fromLatin1("UTF-8")); + ui.encodingComboBox->addItem(tr("(Advanced)", "Encoding"), QString()); + ui.encodingComboBox->setCurrentIndex(ui.encodingComboBox->count() - 1); + + QComboBox *cb(ui.defaultEncodingComboBox); + cb->addItem(tr("(Local codec - %1)", "Encoding").arg(localCodecName), QVariant()); + fillCodecComboBox(cb); + + cb = ui.readEncodingComboBox; + cb->addItem(tr("(Local or unicode)", "Encoding"), QVariant()); + fillCodecComboBox(cb); + + cb = ui.writeEncodingComboBox; + cb->addItem(tr("(Same)", "Encoding"), QVariant()); + fillCodecComboBox(cb); } - QVariant ConfigEditorWidget::defaultSetting(const QString &key) { - if (key == QLatin1String("ShowLineNumberArea")) - return true; - else if (key == QLatin1String("Font")) - return qApp->font().toString(); - else if (key == QLatin1String("ShowWhiteSpaces")) - return false; - else if (key == QLatin1String("ShowTabulators")) - return false; - else if (key == QLatin1String("ShowMatchingBrackets")) - return true; - else if (key == QLatin1String("ColorWhiteSpaces")) - return QColor(Qt::gray); - else if (key == QLatin1String("ColorTabulators")) - return QColor(Qt::gray); - else if (key == QLatin1String("ColorMatchingBrackets")) - return QColor(Qt::darkGreen); - else if (key == QLatin1String("ShowHighlightCurrentLine")) - return true; - else if (key == QLatin1String("ColorHighlightCurrentLine")) - { - const QColor lineColor(QApplication::palette().color(QPalette::Normal, QPalette::Base)); - return lineColor.darker(105); - } - else if (key == QLatin1String("UseCompletion")) - return true; - return QVariant(); + if (key == QLatin1String("ShowLineNumberArea")) + return true; + else if (key == QLatin1String("Font")) + return qApp->font().toString(); + else if (key == QLatin1String("ShowWhiteSpaces")) + return false; + else if (key == QLatin1String("ShowTabulators")) + return false; + else if (key == QLatin1String("ShowMatchingBrackets")) + return true; + else if (key == QLatin1String("ColorWhiteSpaces")) + return QColor(Qt::gray); + else if (key == QLatin1String("ColorTabulators")) + return QColor(Qt::gray); + else if (key == QLatin1String("ColorMatchingBrackets")) + return QColor(Qt::darkGreen); + else if (key == QLatin1String("ShowHighlightCurrentLine")) + return true; + else if (key == QLatin1String("ColorHighlightCurrentLine")) { + const QColor lineColor(QApplication::palette().color(QPalette::Normal, QPalette::Base)); + return lineColor.darker(105); + } else if (key == QLatin1String("UseCompletion")) + return true; + return QVariant(); } void ConfigEditorWidget::readSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); - ui.showLineNumberAreaCheck->setChecked(settings.value(QLatin1String("ShowLineNumberArea"), defaultSetting(QLatin1String("ShowLineNumberArea"))).toBool()); - m_generalFont.fromString(settings.value(QLatin1String("Font"), defaultSetting(QLatin1String("Font"))).toString()); - ui.generalFontEdit->setText(m_generalFont.family() + QLatin1Char(' ') + QString::number(m_generalFont.pointSize())); - ui.generalFontEdit->setFont(m_generalFont); - ui.showWhiteSpacesCheck->setChecked(settings.value(QLatin1String("ShowWhiteSpaces"), defaultSetting(QLatin1String("ShowWhiteSpaces"))).toBool()); - ui.showTabulatorsCheck->setChecked(settings.value(QLatin1String("ShowTabulators"), defaultSetting(QLatin1String("ShowTabulators"))).toBool()); - ui.showMatchingBracketsCheck->setChecked(settings.value(QLatin1String("ShowMatchingBrackets"), defaultSetting(QLatin1String("ShowMatchingBrackets"))).toBool()); - ui.whiteSpacesColorButton->setColor(settings.value(QLatin1String("ColorWhiteSpaces"), defaultSetting(QLatin1String("ColorWhiteSpaces"))).value()); - ui.tabulatorsColorButton->setColor(settings.value(QLatin1String("ColorTabulators"), defaultSetting(QLatin1String("ColorTabulators"))).value()); - ui.matchingBracketsColorButton->setColor(settings.value(QLatin1String("ColorMatchingBrackets"), defaultSetting(QLatin1String("ColorMatchingBrackets"))).value()); - ui.highlightCurrentLineCheck->setChecked(settings.value(QLatin1String("ShowHighlightCurrentLine"), defaultSetting(QLatin1String("ShowHighlightCurrentLine"))).toBool()); - ui.highlightCurrentLineColorButton->setColor(settings.value(QLatin1String("ColorHighlightCurrentLine"), defaultSetting(QLatin1String("ColorHighlightCurrentLine"))).value()); - - ui.useCompletionCheck->setChecked(settings.value(QLatin1String("UseCompletion"), defaultSetting(QLatin1String("UseCompletion"))).toBool()); - - // encoding - settings.beginGroup(QLatin1String("encoding")); - selectEncoding(ui.defaultEncodingComboBox, settings.value(QLatin1String("default"))); - selectEncoding(ui.readEncodingComboBox, settings.value(QLatin1String("decoder"))); - selectEncoding(ui.writeEncodingComboBox, settings.value(QLatin1String("encoder"))); - ui.bomCheckBox->setChecked(settings.value(QLatin1String("bom"), true).toBool()); - selectEncoding(ui.encodingComboBox, settings.value(QLatin1String("preset"), QLatin1String("System"))); - settings.endGroup(); - - settings.endGroup(); + QSettings settings; + settings.beginGroup(settingsGroup); + ui.showLineNumberAreaCheck->setChecked( + settings.value(QLatin1String("ShowLineNumberArea"), + defaultSetting(QLatin1String("ShowLineNumberArea"))) + .toBool()); + m_generalFont.fromString( + settings.value(QLatin1String("Font"), defaultSetting(QLatin1String("Font"))) + .toString()); + ui.generalFontEdit->setText(m_generalFont.family() + QLatin1Char(' ') + + QString::number(m_generalFont.pointSize())); + ui.generalFontEdit->setFont(m_generalFont); + ui.showWhiteSpacesCheck->setChecked( + settings.value(QLatin1String("ShowWhiteSpaces"), + defaultSetting(QLatin1String("ShowWhiteSpaces"))) + .toBool()); + ui.showTabulatorsCheck->setChecked( + settings.value(QLatin1String("ShowTabulators"), + defaultSetting(QLatin1String("ShowTabulators"))) + .toBool()); + ui.showMatchingBracketsCheck->setChecked( + settings.value(QLatin1String("ShowMatchingBrackets"), + defaultSetting(QLatin1String("ShowMatchingBrackets"))) + .toBool()); + ui.whiteSpacesColorButton->setColor( + settings.value(QLatin1String("ColorWhiteSpaces"), + defaultSetting(QLatin1String("ColorWhiteSpaces"))) + .value()); + ui.tabulatorsColorButton->setColor( + settings.value(QLatin1String("ColorTabulators"), + defaultSetting(QLatin1String("ColorTabulators"))) + .value()); + ui.matchingBracketsColorButton->setColor( + settings.value(QLatin1String("ColorMatchingBrackets"), + defaultSetting(QLatin1String("ColorMatchingBrackets"))) + .value()); + ui.highlightCurrentLineCheck->setChecked( + settings.value(QLatin1String("ShowHighlightCurrentLine"), + defaultSetting(QLatin1String("ShowHighlightCurrentLine"))) + .toBool()); + ui.highlightCurrentLineColorButton->setColor( + settings.value(QLatin1String("ColorHighlightCurrentLine"), + defaultSetting(QLatin1String("ColorHighlightCurrentLine"))) + .value()); + + ui.useCompletionCheck->setChecked(settings.value(QLatin1String("UseCompletion"), + defaultSetting(QLatin1String("UseCompletion"))) + .toBool()); + + // encoding + settings.beginGroup(QLatin1String("encoding")); + selectEncoding(ui.defaultEncodingComboBox, settings.value(QLatin1String("default"))); + selectEncoding(ui.readEncodingComboBox, settings.value(QLatin1String("decoder"))); + selectEncoding(ui.writeEncodingComboBox, settings.value(QLatin1String("encoder"))); + ui.bomCheckBox->setChecked(settings.value(QLatin1String("bom"), true).toBool()); + selectEncoding(ui.encodingComboBox, + settings.value(QLatin1String("preset"), QLatin1String("System"))); + settings.endGroup(); + + settings.endGroup(); } void ConfigEditorWidget::writeSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); - settings.setValue(QLatin1String("ShowLineNumberArea"), ui.showLineNumberAreaCheck->isChecked()); - settings.setValue(QLatin1String("Font"), m_generalFont.toString()); - settings.setValue(QLatin1String("ShowWhiteSpaces"), ui.showWhiteSpacesCheck->isChecked()); - settings.setValue(QLatin1String("ShowTabulators"), ui.showTabulatorsCheck->isChecked()); - settings.setValue(QLatin1String("ShowMatchingBrackets"), ui.showMatchingBracketsCheck->isChecked()); - settings.setValue(QLatin1String("ColorWhiteSpaces"), ui.whiteSpacesColorButton->color()); - settings.setValue(QLatin1String("ColorTabulators"), ui.tabulatorsColorButton->color()); - settings.setValue(QLatin1String("ColorMatchingBrackets"), ui.matchingBracketsColorButton->color()); - settings.setValue(QLatin1String("ShowHighlightCurrentLine"), ui.highlightCurrentLineCheck->isChecked()); - settings.setValue(QLatin1String("ColorHighlightCurrentLine"), ui.highlightCurrentLineColorButton->color()); - settings.setValue(QLatin1String("UseCompletion"), ui.useCompletionCheck->isChecked()); - - settings.beginGroup(QLatin1String("encoding")); - settings.setValue(QLatin1String("default"), - ui.defaultEncodingComboBox->itemData(ui.defaultEncodingComboBox->currentIndex())); - settings.setValue(QLatin1String("encoder"), - ui.writeEncodingComboBox->itemData(ui.writeEncodingComboBox->currentIndex())); - settings.setValue(QLatin1String("decoder"), - ui.readEncodingComboBox->itemData(ui.readEncodingComboBox->currentIndex())); - settings.setValue(QLatin1String("bom"), ui.bomCheckBox->isChecked()); - settings.setValue(QLatin1String("preset"), - ui.encodingComboBox->itemData(ui.encodingComboBox->currentIndex())); - settings.endGroup(); - settings.endGroup(); + QSettings settings; + settings.beginGroup(settingsGroup); + settings.setValue(QLatin1String("ShowLineNumberArea"), ui.showLineNumberAreaCheck->isChecked()); + settings.setValue(QLatin1String("Font"), m_generalFont.toString()); + settings.setValue(QLatin1String("ShowWhiteSpaces"), ui.showWhiteSpacesCheck->isChecked()); + settings.setValue(QLatin1String("ShowTabulators"), ui.showTabulatorsCheck->isChecked()); + settings.setValue(QLatin1String("ShowMatchingBrackets"), + ui.showMatchingBracketsCheck->isChecked()); + settings.setValue(QLatin1String("ColorWhiteSpaces"), ui.whiteSpacesColorButton->color()); + settings.setValue(QLatin1String("ColorTabulators"), ui.tabulatorsColorButton->color()); + settings.setValue(QLatin1String("ColorMatchingBrackets"), + ui.matchingBracketsColorButton->color()); + settings.setValue(QLatin1String("ShowHighlightCurrentLine"), + ui.highlightCurrentLineCheck->isChecked()); + settings.setValue(QLatin1String("ColorHighlightCurrentLine"), + ui.highlightCurrentLineColorButton->color()); + settings.setValue(QLatin1String("UseCompletion"), ui.useCompletionCheck->isChecked()); + + settings.beginGroup(QLatin1String("encoding")); + settings.setValue( + QLatin1String("default"), + ui.defaultEncodingComboBox->itemData(ui.defaultEncodingComboBox->currentIndex())); + settings.setValue(QLatin1String("encoder"), + ui.writeEncodingComboBox->itemData(ui.writeEncodingComboBox->currentIndex())); + settings.setValue(QLatin1String("decoder"), + ui.readEncodingComboBox->itemData(ui.readEncodingComboBox->currentIndex())); + settings.setValue(QLatin1String("bom"), ui.bomCheckBox->isChecked()); + settings.setValue(QLatin1String("preset"), + ui.encodingComboBox->itemData(ui.encodingComboBox->currentIndex())); + settings.endGroup(); + settings.endGroup(); } void ConfigEditorWidget::selectFont() { - bool ok; - const QFont newFont = FontDialog::getFont(&ok, m_generalFont, this); - if (ok) - { - m_generalFont = newFont; - ui.generalFontEdit->setText(m_generalFont.family() + QLatin1Char(' ') + QString::number(m_generalFont.pointSize())); - ui.generalFontEdit->setFont(m_generalFont); - } + bool ok; + const QFont newFont = FontDialog::getFont(&ok, m_generalFont, this); + if (ok) { + m_generalFont = newFont; + ui.generalFontEdit->setText(m_generalFont.family() + QLatin1Char(' ') + + QString::number(m_generalFont.pointSize())); + ui.generalFontEdit->setFont(m_generalFont); + } } - class ComboItem { public: - ComboItem() {} - ComboItem(const QString &text, const QVariant &data): - text(text), data(data) - {} - QString text; - QVariant data; - bool operator <(const ComboItem &other) const {return QString::compare(this->text, other.text, Qt::CaseInsensitive) < 0;} + ComboItem() { } + ComboItem(const QString &text, const QVariant &data) : text(text), data(data) { } + QString text; + QVariant data; + bool operator<(const ComboItem &other) const + { + return QString::compare(this->text, other.text, Qt::CaseInsensitive) < 0; + } }; void ConfigEditorWidget::fillCodecComboBox(QComboBox *cb) { - const QList ca (QTextCodec::availableCodecs()); - QVector ciList; ciList.reserve(ca.length()); - Q_FOREACH(const QByteArray &ba , ca) - ciList.append(ComboItem(codecNameToString(ba), ba)); - qSort(ciList); - Q_FOREACH (const ComboItem& ci, ciList) { - cb->addItem(ci.text, ci.data); - } + const QList ca(QTextCodec::availableCodecs()); + QVector ciList; + ciList.reserve(ca.length()); + Q_FOREACH (const QByteArray &ba, ca) + ciList.append(ComboItem(codecNameToString(ba), ba)); + qSort(ciList); + Q_FOREACH (const ComboItem &ci, ciList) { + cb->addItem(ci.text, ci.data); + } } void ConfigEditorWidget::selectEncoding(QComboBox *cb, const QVariant &codecName) { - for(int i=0; icount(); ++i) { - if(cb->itemData(i) == codecName) - { - cb->setCurrentIndex(i); - return ; - } - } + for (int i = 0; i < cb->count(); ++i) { + if (cb->itemData(i) == codecName) { + cb->setCurrentIndex(i); + return; + } + } } - - void ConfigEditorWidget::on_encodingComboBox_currentIndexChanged(int index) { - bool bShowAdvEncondingOptions = (index == -1); - - // (!bShowAdvEncondingOptions) is true when the widget is initialized. - if(Q_LIKELY( !bShowAdvEncondingOptions) ) - { - QString key=ui.encodingComboBox->itemData(index).toString(); - if (key.isEmpty()) - { - bShowAdvEncondingOptions = true; - } - else - { - QVariant de, re, we; - bool bom ; - if (key.compare(QString::fromLatin1("UTF-8+BOM"))==0) - { - de = QString::fromLatin1("UTF-8"); - we = de; - bom = true; - } - else if (key.compare(QString::fromLatin1("UTF-8"))==0) - { - de = QString::fromLatin1("UTF-8"); - we = de; - bom = false; - } - else // if (key.compare(QString::fromLatin1("System"))==0) - { - bom = true; - } - - selectEncoding(ui.defaultEncodingComboBox,de); - selectEncoding(ui.readEncodingComboBox,re); - selectEncoding(ui.writeEncodingComboBox,we); - ui.bomCheckBox->setChecked(bom); - } - } - ui.encodingAdvWidget->setVisible(bShowAdvEncondingOptions); - - + bool bShowAdvEncondingOptions = (index == -1); + + // (!bShowAdvEncondingOptions) is true when the widget is initialized. + if (Q_LIKELY(!bShowAdvEncondingOptions)) { + QString key = ui.encodingComboBox->itemData(index).toString(); + if (key.isEmpty()) { + bShowAdvEncondingOptions = true; + } else { + QVariant de, re, we; + bool bom; + if (key.compare(QString::fromLatin1("UTF-8+BOM")) == 0) { + de = QString::fromLatin1("UTF-8"); + we = de; + bom = true; + } else if (key.compare(QString::fromLatin1("UTF-8")) == 0) { + de = QString::fromLatin1("UTF-8"); + we = de; + bom = false; + } else // if (key.compare(QString::fromLatin1("System"))==0) + { + bom = true; + } + + selectEncoding(ui.defaultEncodingComboBox, de); + selectEncoding(ui.readEncodingComboBox, re); + selectEncoding(ui.writeEncodingComboBox, we); + ui.bomCheckBox->setChecked(bom); + } + } + ui.encodingAdvWidget->setVisible(bShowAdvEncondingOptions); } -QString ConfigEditorWidget::codecNameToString(const QByteArray& codecName) +QString ConfigEditorWidget::codecNameToString(const QByteArray &codecName) { - return QString::fromLatin1(codecName.constData(), codecName.length()); + return QString::fromLatin1(codecName.constData(), codecName.length()); } -QString ConfigEditorWidget::codecNameToString(QTextCodec *codec){return codecNameToString(codec->name());} +QString ConfigEditorWidget::codecNameToString(QTextCodec *codec) +{ + return codecNameToString(codec->name()); +} diff --git a/app/configeditorwidget.h b/app/configeditorwidget.h index d2b4fc0..5d823f6 100644 --- a/app/configeditorwidget.h +++ b/app/configeditorwidget.h @@ -2,10 +2,9 @@ * Copyright (C) 2008, 2009, 2013, 2014 by Glad Deschrijver * * * * Copyright (C) 2016 by G. Prudhomme * - * * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * + * * * This program is free + *software; you can redistribute it and/or modify * it under the terms of the GNU General Public + *License as published by * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * @@ -27,32 +26,33 @@ class QComboBox; class ConfigEditorWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ConfigEditorWidget(QWidget *parent = 0); + explicit ConfigEditorWidget(QWidget *parent = 0); - static QVariant defaultSetting(const QString &key); + static QVariant defaultSetting(const QString &key); - void readSettings(const QString &settingsGroup); - void writeSettings(const QString &settingsGroup); + void readSettings(const QString &settingsGroup); + void writeSettings(const QString &settingsGroup); + + void initializeEncoding(); - void initializeEncoding(); protected: - Ui::ConfigEditorWidget ui; + Ui::ConfigEditorWidget ui; private Q_SLOTS: - void selectFont(); + void selectFont(); - void on_encodingComboBox_currentIndexChanged(int index); + void on_encodingComboBox_currentIndexChanged(int index); private: - QFont m_generalFont; + QFont m_generalFont; - static QString codecNameToString(const QByteArray &codecName); - static QString codecNameToString(QTextCodec *codec); - static void fillCodecComboBox(QComboBox *cb); - static void selectEncoding(QComboBox *cb, const QVariant& codecName); - }; + static QString codecNameToString(const QByteArray &codecName); + static QString codecNameToString(QTextCodec *codec); + static void fillCodecComboBox(QComboBox *cb); + static void selectEncoding(QComboBox *cb, const QVariant &codecName); +}; #endif diff --git a/app/configgeneralwidget.cpp b/app/configgeneralwidget.cpp index ece3a3a..a3f3254 100644 --- a/app/configgeneralwidget.cpp +++ b/app/configgeneralwidget.cpp @@ -28,137 +28,141 @@ #include "../common/utils/urlcompletion.h" #include "../common/utils/url.h" -ConfigGeneralWidget::ConfigGeneralWidget(QWidget *parent) - : QWidget(parent) +ConfigGeneralWidget::ConfigGeneralWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); + ui.setupUi(this); #ifdef KTIKZ_USE_KDE - ui.historyLengthLabel->setVisible(false); - ui.historyLengthSpinBox->setVisible(false); - ui.toolBarStyleLabel->setVisible(false); - ui.toolBarStyleComboBox->setVisible(false); + ui.historyLengthLabel->setVisible(false); + ui.historyLengthSpinBox->setVisible(false); + ui.toolBarStyleLabel->setVisible(false); + ui.toolBarStyleComboBox->setVisible(false); #endif #ifdef KTIKZ_USE_KTEXTEDITOR - ui.editorWidgetComboBox->addItem(tr("Qt Editor", "TextEditor"), QString()); - ui.editorWidgetComboBox->addItem(tr("KDE Frameworks Editor", "TextEditor"), QString()); + ui.editorWidgetComboBox->addItem(tr("Qt Editor", "TextEditor"), QString()); + ui.editorWidgetComboBox->addItem(tr("KDE Frameworks Editor", "TextEditor"), QString()); #endif - m_urlCompletion = new UrlCompletion(this); - ui.tikzDocEdit->setCompletionObject(m_urlCompletion); - ui.latexEdit->setCompletionObject(m_urlCompletion); - ui.pdftopsEdit->setCompletionObject(m_urlCompletion); - ui.editorEdit->setCompletionObject(m_urlCompletion); - - ui.tikzDocButton->setIcon(Icon(QLatin1String("document-open"))); - ui.latexButton->setIcon(Icon(QLatin1String("document-open"))); - ui.pdftopsButton->setIcon(Icon(QLatin1String("document-open"))); - ui.editorButton->setIcon(Icon(QLatin1String("document-open"))); - - connect(ui.tikzDocButton, SIGNAL(clicked()), this, SLOT(browseCommand())); - connect(ui.tikzDocSearchButton, SIGNAL(clicked()), this, SLOT(searchTikzDocumentation())); - connect(ui.latexButton, SIGNAL(clicked()), this, SLOT(browseCommand())); - connect(ui.pdftopsButton, SIGNAL(clicked()), this, SLOT(browseCommand())); - connect(ui.editorButton, SIGNAL(clicked()), this, SLOT(browseCommand())); + m_urlCompletion = new UrlCompletion(this); + ui.tikzDocEdit->setCompletionObject(m_urlCompletion); + ui.latexEdit->setCompletionObject(m_urlCompletion); + ui.pdftopsEdit->setCompletionObject(m_urlCompletion); + ui.editorEdit->setCompletionObject(m_urlCompletion); + + ui.tikzDocButton->setIcon(Icon(QLatin1String("document-open"))); + ui.latexButton->setIcon(Icon(QLatin1String("document-open"))); + ui.pdftopsButton->setIcon(Icon(QLatin1String("document-open"))); + ui.editorButton->setIcon(Icon(QLatin1String("document-open"))); + + connect(ui.tikzDocButton, SIGNAL(clicked()), this, SLOT(browseCommand())); + connect(ui.tikzDocSearchButton, SIGNAL(clicked()), this, SLOT(searchTikzDocumentation())); + connect(ui.latexButton, SIGNAL(clicked()), this, SLOT(browseCommand())); + connect(ui.pdftopsButton, SIGNAL(clicked()), this, SLOT(browseCommand())); + connect(ui.editorButton, SIGNAL(clicked()), this, SLOT(browseCommand())); } ConfigGeneralWidget::~ConfigGeneralWidget() { - delete m_urlCompletion; + delete m_urlCompletion; } void ConfigGeneralWidget::readSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); + QSettings settings; + settings.beginGroup(settingsGroup); #ifndef KTIKZ_USE_KDE - ui.historyLengthSpinBox->setValue(settings.value(QLatin1String("RecentFilesNumber"), 10).toInt()); + ui.historyLengthSpinBox->setValue( + settings.value(QLatin1String("RecentFilesNumber"), 10).toInt()); #endif #ifdef KTIKZ_USE_KTEXTEDITOR - ui.editorWidgetComboBox->setCurrentIndex(settings.value(QLatin1String("EditorWidget"), 0).toInt()); + ui.editorWidgetComboBox->setCurrentIndex( + settings.value(QLatin1String("EditorWidget"), 0).toInt()); #endif - ui.commandsInDockCheck->setChecked(settings.value(QLatin1String("CommandsInDock"), false).toBool()); - ui.tikzDocEdit->setText(TikzDocumentationController::tikzDocumentationPath()); - ui.latexEdit->setText(settings.value(QLatin1String("LatexCommand"), QLatin1String("pdflatex")).toString()); - ui.pdftopsEdit->setText(settings.value(QLatin1String("PdftopsCommand"), QLatin1String("pdftops")).toString()); - ui.editorEdit->setText(settings.value(QLatin1String("TemplateEditor"), QLatin1String("")).toString()); - ui.replaceEdit->setText(settings.value(QLatin1String("TemplateReplaceText"), QLatin1String("<>")).toString()); - settings.endGroup(); + ui.commandsInDockCheck->setChecked( + settings.value(QLatin1String("CommandsInDock"), false).toBool()); + ui.tikzDocEdit->setText(TikzDocumentationController::tikzDocumentationPath()); + ui.latexEdit->setText( + settings.value(QLatin1String("LatexCommand"), QLatin1String("pdflatex")).toString()); + ui.pdftopsEdit->setText( + settings.value(QLatin1String("PdftopsCommand"), QLatin1String("pdftops")).toString()); + ui.editorEdit->setText( + settings.value(QLatin1String("TemplateEditor"), QLatin1String("")).toString()); + ui.replaceEdit->setText( + settings.value(QLatin1String("TemplateReplaceText"), QLatin1String("<>")).toString()); + settings.endGroup(); #ifndef KTIKZ_USE_KDE - settings.beginGroup(QLatin1String("MainWindow")); - ui.toolBarStyleComboBox->setCurrentIndex(settings.value(QLatin1String("ToolBarStyle"), 0).toInt()); - settings.endGroup(); + settings.beginGroup(QLatin1String("MainWindow")); + ui.toolBarStyleComboBox->setCurrentIndex( + settings.value(QLatin1String("ToolBarStyle"), 0).toInt()); + settings.endGroup(); #endif } void ConfigGeneralWidget::writeSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); + QSettings settings; + settings.beginGroup(settingsGroup); #ifndef KTIKZ_USE_KDE - settings.setValue(QLatin1String("RecentFilesNumber"), ui.historyLengthSpinBox->value()); + settings.setValue(QLatin1String("RecentFilesNumber"), ui.historyLengthSpinBox->value()); #endif #ifdef KTIKZ_USE_KTEXTEDITOR - settings.setValue(QLatin1String("EditorWidget"), ui.editorWidgetComboBox->currentIndex()); + settings.setValue(QLatin1String("EditorWidget"), ui.editorWidgetComboBox->currentIndex()); #endif - settings.setValue(QLatin1String("CommandsInDock"), ui.commandsInDockCheck->isChecked()); - TikzDocumentationController::storeTikzDocumentationPath(ui.tikzDocEdit->text()); - settings.setValue(QLatin1String("LatexCommand"), ui.latexEdit->text()); - settings.setValue(QLatin1String("PdftopsCommand"), ui.pdftopsEdit->text()); - settings.setValue(QLatin1String("TemplateEditor"), ui.editorEdit->text()); - settings.setValue(QLatin1String("TemplateReplaceText"), ui.replaceEdit->text()); - settings.endGroup(); + settings.setValue(QLatin1String("CommandsInDock"), ui.commandsInDockCheck->isChecked()); + TikzDocumentationController::storeTikzDocumentationPath(ui.tikzDocEdit->text()); + settings.setValue(QLatin1String("LatexCommand"), ui.latexEdit->text()); + settings.setValue(QLatin1String("PdftopsCommand"), ui.pdftopsEdit->text()); + settings.setValue(QLatin1String("TemplateEditor"), ui.editorEdit->text()); + settings.setValue(QLatin1String("TemplateReplaceText"), ui.replaceEdit->text()); + settings.endGroup(); #ifndef KTIKZ_USE_KDE - settings.beginGroup(QLatin1String("MainWindow")); - settings.setValue(QLatin1String("ToolBarStyle"), ui.toolBarStyleComboBox->currentIndex()); - settings.endGroup(); + settings.beginGroup(QLatin1String("MainWindow")); + settings.setValue(QLatin1String("ToolBarStyle"), ui.toolBarStyleComboBox->currentIndex()); + settings.endGroup(); #endif } void ConfigGeneralWidget::searchTikzDocumentation() { - const QString tikzDocFile = TikzDocumentationController::searchTikzDocumentationInTexTree(); - if (tikzDocFile.isEmpty()) - MessageBox::sorry(this, tr("Cannot find TikZ documentation."), - KtikzApplication::applicationName()); - else - ui.tikzDocEdit->setText(tikzDocFile); + const QString tikzDocFile = TikzDocumentationController::searchTikzDocumentationInTexTree(); + if (tikzDocFile.isEmpty()) + MessageBox::sorry(this, tr("Cannot find TikZ documentation."), + KtikzApplication::applicationName()); + else + ui.tikzDocEdit->setText(tikzDocFile); } void ConfigGeneralWidget::browseCommand(QLineEdit *lineEdit, bool isProgram) { - QString location; - if (isProgram) - { - Url url = FileDialog::getOpenUrl(this, tr("Browse program"), Url(QDir::rootPath())); - location = url.path(); - } - else - { - const QString oldLocation = lineEdit->text(); - Url url = FileDialog::getOpenUrl(this, tr("Browse file"), - Url(!oldLocation.isEmpty() ? oldLocation : QDir::homePath())); - location = url.path(); - } - if (!location.isEmpty()) - { - location.replace(QLatin1Char('\\'), QLatin1Char('/')); - lineEdit->setText(location); - } + QString location; + if (isProgram) { + Url url = FileDialog::getOpenUrl(this, tr("Browse program"), Url(QDir::rootPath())); + location = url.path(); + } else { + const QString oldLocation = lineEdit->text(); + Url url = FileDialog::getOpenUrl( + this, tr("Browse file"), + Url(!oldLocation.isEmpty() ? oldLocation : QDir::homePath())); + location = url.path(); + } + if (!location.isEmpty()) { + location.replace(QLatin1Char('\\'), QLatin1Char('/')); + lineEdit->setText(location); + } } void ConfigGeneralWidget::browseCommand() { - QToolButton *button = qobject_cast(sender()); - if (button->objectName() == QLatin1String("latexButton")) - browseCommand(ui.latexEdit); - else if (button->objectName() == QLatin1String("pdftopsButton")) - browseCommand(ui.pdftopsEdit); - else if (button->objectName() == QLatin1String("editorButton")) - browseCommand(ui.editorEdit); - else if (button->objectName() == QLatin1String("tikzDocButton")) - browseCommand(ui.tikzDocEdit, false); + QToolButton *button = qobject_cast(sender()); + if (button->objectName() == QLatin1String("latexButton")) + browseCommand(ui.latexEdit); + else if (button->objectName() == QLatin1String("pdftopsButton")) + browseCommand(ui.pdftopsEdit); + else if (button->objectName() == QLatin1String("editorButton")) + browseCommand(ui.editorEdit); + else if (button->objectName() == QLatin1String("tikzDocButton")) + browseCommand(ui.tikzDocEdit, false); } diff --git a/app/configgeneralwidget.h b/app/configgeneralwidget.h index 20eba54..7788f75 100644 --- a/app/configgeneralwidget.h +++ b/app/configgeneralwidget.h @@ -25,26 +25,26 @@ class UrlCompletion; class ConfigGeneralWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ConfigGeneralWidget(QWidget *parent = 0); - ~ConfigGeneralWidget(); + explicit ConfigGeneralWidget(QWidget *parent = 0); + ~ConfigGeneralWidget(); - void readSettings(const QString &settingsGroup); - void writeSettings(const QString &settingsGroup); + void readSettings(const QString &settingsGroup); + void writeSettings(const QString &settingsGroup); protected: - Ui::ConfigGeneralWidget ui; + Ui::ConfigGeneralWidget ui; private Q_SLOTS: - void searchTikzDocumentation(); - void browseCommand(); + void searchTikzDocumentation(); + void browseCommand(); private: - void browseCommand(QLineEdit *lineEdit, bool isProgram = true); + void browseCommand(QLineEdit *lineEdit, bool isProgram = true); - UrlCompletion *m_urlCompletion; + UrlCompletion *m_urlCompletion; }; #endif diff --git a/app/configpreviewwidget.cpp b/app/configpreviewwidget.cpp index b900747..c796a94 100644 --- a/app/configpreviewwidget.cpp +++ b/app/configpreviewwidget.cpp @@ -20,50 +20,47 @@ #include -ConfigPreviewWidget::ConfigPreviewWidget(QWidget *parent) - : QWidget(parent) +ConfigPreviewWidget::ConfigPreviewWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); + ui.setupUi(this); } -ConfigPreviewWidget::~ConfigPreviewWidget() -{ -} +ConfigPreviewWidget::~ConfigPreviewWidget() { } void ConfigPreviewWidget::readSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); - if (settings.value(QLatin1String("BuildAutomatically"), true).toBool()) - ui.buildAutomaticallyRadio->setChecked(true); - else - ui.buildManuallyRadio->setChecked(true); + QSettings settings; + settings.beginGroup(settingsGroup); + if (settings.value(QLatin1String("BuildAutomatically"), true).toBool()) + ui.buildAutomaticallyRadio->setChecked(true); + else + ui.buildManuallyRadio->setChecked(true); - ui.showCoordinatesCheck->setChecked(settings.value(QLatin1String("ShowCoordinates"), true).toBool()); - const int precision = settings.value(QLatin1String("ShowCoordinatesPrecision"), -1).toInt(); - if (precision < 0) - { - ui.bestPrecisionRadio->setChecked(true); - } - else - { - ui.specifyPrecisionRadio->setChecked(true); - ui.specifyPrecisionSpinBox->setValue(precision); - } - ui.backgroundColorButton->setColor(settings.value(QLatin1String("PreviewBackgroundColor")).value()); - settings.endGroup(); + ui.showCoordinatesCheck->setChecked( + settings.value(QLatin1String("ShowCoordinates"), true).toBool()); + const int precision = settings.value(QLatin1String("ShowCoordinatesPrecision"), -1).toInt(); + if (precision < 0) { + ui.bestPrecisionRadio->setChecked(true); + } else { + ui.specifyPrecisionRadio->setChecked(true); + ui.specifyPrecisionSpinBox->setValue(precision); + } + ui.backgroundColorButton->setColor( + settings.value(QLatin1String("PreviewBackgroundColor")).value()); + settings.endGroup(); } void ConfigPreviewWidget::writeSettings(const QString &settingsGroup) { - QSettings settings; - settings.beginGroup(settingsGroup); - settings.setValue(QLatin1String("BuildAutomatically"), ui.buildAutomaticallyRadio->isChecked()); - settings.setValue(QLatin1String("ShowCoordinates"), ui.showCoordinatesCheck->isChecked()); - if (ui.bestPrecisionRadio->isChecked()) - settings.setValue(QLatin1String("ShowCoordinatesPrecision"), -1); - else - settings.setValue(QLatin1String("ShowCoordinatesPrecision"), ui.specifyPrecisionSpinBox->value()); + QSettings settings; + settings.beginGroup(settingsGroup); + settings.setValue(QLatin1String("BuildAutomatically"), ui.buildAutomaticallyRadio->isChecked()); + settings.setValue(QLatin1String("ShowCoordinates"), ui.showCoordinatesCheck->isChecked()); + if (ui.bestPrecisionRadio->isChecked()) + settings.setValue(QLatin1String("ShowCoordinatesPrecision"), -1); + else + settings.setValue(QLatin1String("ShowCoordinatesPrecision"), + ui.specifyPrecisionSpinBox->value()); settings.setValue(QLatin1String("PreviewBackgroundColor"), ui.backgroundColorButton->color()); settings.endGroup(); } diff --git a/app/configpreviewwidget.h b/app/configpreviewwidget.h index 50873fe..7357c07 100644 --- a/app/configpreviewwidget.h +++ b/app/configpreviewwidget.h @@ -23,17 +23,17 @@ class ConfigPreviewWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ConfigPreviewWidget(QWidget *parent = 0); - ~ConfigPreviewWidget(); + explicit ConfigPreviewWidget(QWidget *parent = 0); + ~ConfigPreviewWidget(); - void readSettings(const QString &settingsGroup); - void writeSettings(const QString &settingsGroup); + void readSettings(const QString &settingsGroup); + void writeSettings(const QString &settingsGroup); protected: - Ui::ConfigPreviewWidget ui; + Ui::ConfigPreviewWidget ui; }; #endif // KTIKZ_CONFIGPREVIEWWIDGET_H diff --git a/app/editgotolinewidget.cpp b/app/editgotolinewidget.cpp index 1c0721e..f9dc105 100644 --- a/app/editgotolinewidget.cpp +++ b/app/editgotolinewidget.cpp @@ -23,48 +23,46 @@ GoToLineWidget::GoToLineWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); - ui.spinBoxGo->setMinimum(1); - ui.pushButtonClose->setIcon(Icon(QLatin1String("dialog-cancel"))); + ui.setupUi(this); + ui.spinBoxGo->setMinimum(1); + ui.pushButtonClose->setIcon(Icon(QLatin1String("dialog-cancel"))); - setFocusProxy(ui.spinBoxGo); + setFocusProxy(ui.spinBoxGo); - connect(ui.pushButtonGo, SIGNAL(clicked()), this, SLOT(goToLine())); - connect(ui.pushButtonClose, SIGNAL(clicked()), this, SLOT(hide())); + connect(ui.pushButtonGo, SIGNAL(clicked()), this, SLOT(goToLine())); + connect(ui.pushButtonClose, SIGNAL(clicked()), this, SLOT(hide())); } -GoToLineWidget::~GoToLineWidget() -{ -} +GoToLineWidget::~GoToLineWidget() { } void GoToLineWidget::goToLine() { - Q_EMIT goToLine(ui.spinBoxGo->value() - 1); + Q_EMIT goToLine(ui.spinBoxGo->value() - 1); } void GoToLineWidget::setMaximumValue(int maximumValue) { - ui.spinBoxGo->setMaximum(maximumValue); + ui.spinBoxGo->setMaximum(maximumValue); } void GoToLineWidget::setValue(int value) { - ui.spinBoxGo->setValue(value); - ui.spinBoxGo->setFocus(); - ui.spinBoxGo->selectAll(); + ui.spinBoxGo->setValue(value); + ui.spinBoxGo->setFocus(); + ui.spinBoxGo->selectAll(); } void GoToLineWidget::hide() { - setVisible(false); - Q_EMIT focusEditor(); + setVisible(false); + Q_EMIT focusEditor(); } void GoToLineWidget::keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Escape) - hide(); - else if (event->key() == Qt::Key_Return) - goToLine(); - QWidget::keyPressEvent(event); + if (event->key() == Qt::Key_Escape) + hide(); + else if (event->key() == Qt::Key_Return) + goToLine(); + QWidget::keyPressEvent(event); } diff --git a/app/editgotolinewidget.h b/app/editgotolinewidget.h index 1cbe7f8..33da2e7 100644 --- a/app/editgotolinewidget.h +++ b/app/editgotolinewidget.h @@ -23,29 +23,29 @@ class GoToLineWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit GoToLineWidget(QWidget *parent = 0); - ~GoToLineWidget(); - void setMaximumValue(int maximumValue); - void setValue(int value); + explicit GoToLineWidget(QWidget *parent = 0); + ~GoToLineWidget(); + void setMaximumValue(int maximumValue); + void setValue(int value); public Q_SLOTS: - void goToLine(); + void goToLine(); Q_SIGNALS: - void goToLine(int lineNumber); - void focusEditor(); + void goToLine(int lineNumber); + void focusEditor(); protected: - virtual void keyPressEvent(QKeyEvent *event); + virtual void keyPressEvent(QKeyEvent *event); protected Q_SLOTS: - void hide(); + void hide(); private: - Ui::GoToLineWidget ui; + Ui::GoToLineWidget ui; }; #endif diff --git a/app/editindentwidget.cpp b/app/editindentwidget.cpp index 50d31c4..43fc24b 100644 --- a/app/editindentwidget.cpp +++ b/app/editindentwidget.cpp @@ -25,86 +25,90 @@ IndentWidget::IndentWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); - ui.pushButtonClose->setIcon(Icon(QLatin1String("dialog-cancel"))); + ui.setupUi(this); + ui.pushButtonClose->setIcon(Icon(QLatin1String("dialog-cancel"))); - readSettings(); + readSettings(); - connect(ui.pushButtonIndent, SIGNAL(clicked()), this, SLOT(indent())); - connect(ui.pushButtonClose, SIGNAL(clicked()), this, SLOT(hide())); + connect(ui.pushButtonIndent, SIGNAL(clicked()), this, SLOT(indent())); + connect(ui.pushButtonClose, SIGNAL(clicked()), this, SLOT(hide())); } -IndentWidget::~IndentWidget() -{ -} +IndentWidget::~IndentWidget() { } void IndentWidget::readSettings() { - QSettings settings; - settings.beginGroup(QLatin1String("Editor")); - ui.radioButtonSpaces->setChecked(settings.value(QLatin1String("Indent/InsertChar"), '\t').toChar() == QLatin1Char(' ')); - ui.radioButtonTabs->setChecked(settings.value(QLatin1String("Indent/InsertChar"), '\t').toChar() != QLatin1Char(' ')); - ui.spinBoxSpaces->setValue(settings.value(QLatin1String("Indent/NumberOfSpaces"), 2).toInt()); - ui.spinBoxTabs->setValue(settings.value(QLatin1String("Indent/NumberOfTabs"), 1).toInt()); - settings.endGroup(); + QSettings settings; + settings.beginGroup(QLatin1String("Editor")); + ui.radioButtonSpaces->setChecked( + settings.value(QLatin1String("Indent/InsertChar"), '\t').toChar() == QLatin1Char(' ')); + ui.radioButtonTabs->setChecked(settings.value(QLatin1String("Indent/InsertChar"), '\t').toChar() + != QLatin1Char(' ')); + ui.spinBoxSpaces->setValue(settings.value(QLatin1String("Indent/NumberOfSpaces"), 2).toInt()); + ui.spinBoxTabs->setValue(settings.value(QLatin1String("Indent/NumberOfTabs"), 1).toInt()); + settings.endGroup(); } void IndentWidget::writeSettings() { - QSettings settings; - settings.beginGroup(QLatin1String("Editor")); - settings.setValue(QLatin1String("Indent/InsertChar"), ui.radioButtonSpaces->isChecked() ? QVariant::fromValue(' ') : QVariant::fromValue('\t')); - settings.setValue(QLatin1String("Indent/NumberOfSpaces"), ui.spinBoxSpaces->value()); - settings.setValue(QLatin1String("Indent/NumberOfTabs"), ui.spinBoxTabs->value()); - settings.endGroup(); + QSettings settings; + settings.beginGroup(QLatin1String("Editor")); + settings.setValue(QLatin1String("Indent/InsertChar"), + ui.radioButtonSpaces->isChecked() ? QVariant::fromValue(' ') + : QVariant::fromValue('\t')); + settings.setValue(QLatin1String("Indent/NumberOfSpaces"), ui.spinBoxSpaces->value()); + settings.setValue(QLatin1String("Indent/NumberOfTabs"), ui.spinBoxTabs->value()); + settings.endGroup(); } void IndentWidget::setUnindenting(bool isUnindenting) { - m_isUnindenting = isUnindenting; - setWindowTitle(m_isUnindenting ? tr("Unindent") : tr("Indent")); - ui.pushButtonIndent->setText(m_isUnindenting ? tr("Unin&dent") : tr("In&dent")); + m_isUnindenting = isUnindenting; + setWindowTitle(m_isUnindenting ? tr("Unindent") : tr("Indent")); + ui.pushButtonIndent->setText(m_isUnindenting ? tr("Unin&dent") : tr("In&dent")); } QChar IndentWidget::insertChar() const { - return ui.radioButtonSpaces->isChecked() ? QLatin1Char(' ') : QLatin1Char('\t'); + return ui.radioButtonSpaces->isChecked() ? QLatin1Char(' ') : QLatin1Char('\t'); } int IndentWidget::numOfInserts() const { - return ui.radioButtonSpaces->isChecked() ? ui.spinBoxSpaces->value() : ui.spinBoxTabs->value(); + return ui.radioButtonSpaces->isChecked() ? ui.spinBoxSpaces->value() : ui.spinBoxTabs->value(); } void IndentWidget::indent() { - const QChar insertChar = ui.radioButtonSpaces->isChecked() ? QLatin1Char(' ') : QLatin1Char('\t'); - const int numOfInserts = ui.radioButtonSpaces->isChecked() ? ui.spinBoxSpaces->value() : ui.spinBoxTabs->value(); - Q_EMIT indent(insertChar, numOfInserts, m_isUnindenting); - writeSettings(); + const QChar insertChar = + ui.radioButtonSpaces->isChecked() ? QLatin1Char(' ') : QLatin1Char('\t'); + const int numOfInserts = + ui.radioButtonSpaces->isChecked() ? ui.spinBoxSpaces->value() : ui.spinBoxTabs->value(); + Q_EMIT indent(insertChar, numOfInserts, m_isUnindenting); + writeSettings(); } void IndentWidget::hide() { - setVisible(false); - Q_EMIT hidden(); - readSettings(); + setVisible(false); + Q_EMIT hidden(); + readSettings(); } void IndentWidget::showEvent(QShowEvent *event) { - if (ui.radioButtonSpaces->isChecked()) - setFocusProxy(ui.radioButtonSpaces); - else - setFocusProxy(ui.radioButtonTabs); - QWidget::showEvent(event); + if (ui.radioButtonSpaces->isChecked()) + setFocusProxy(ui.radioButtonSpaces); + else + setFocusProxy(ui.radioButtonTabs); + QWidget::showEvent(event); } void IndentWidget::keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Escape) - hide(); - else if (event->key() == Qt::Key_Return) - indent(); - QWidget::keyPressEvent(event); + if (event->key() == Qt::Key_Escape) + hide(); + else if (event->key() == Qt::Key_Return) + indent(); + QWidget::keyPressEvent(event); } diff --git a/app/editindentwidget.h b/app/editindentwidget.h index b067d00..60f19cf 100644 --- a/app/editindentwidget.h +++ b/app/editindentwidget.h @@ -23,34 +23,34 @@ class IndentWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit IndentWidget(QWidget *parent = 0); - ~IndentWidget(); + explicit IndentWidget(QWidget *parent = 0); + ~IndentWidget(); - void setUnindenting(bool isUnindenting = true); - QChar insertChar() const; - int numOfInserts() const; + void setUnindenting(bool isUnindenting = true); + QChar insertChar() const; + int numOfInserts() const; Q_SIGNALS: - void indent(QChar insertChar, int numOfInserts, bool isUnindenting); - void hidden(); + void indent(QChar insertChar, int numOfInserts, bool isUnindenting); + void hidden(); protected: - virtual void showEvent(QShowEvent *event); - virtual void keyPressEvent(QKeyEvent *event); + virtual void showEvent(QShowEvent *event); + virtual void keyPressEvent(QKeyEvent *event); private Q_SLOTS: - void indent(); - void hide(); + void indent(); + void hide(); private: - void readSettings(); - void writeSettings(); + void readSettings(); + void writeSettings(); - Ui::IndentWidget ui; - bool m_isUnindenting; + Ui::IndentWidget ui; + bool m_isUnindenting; }; #endif diff --git a/app/editreplacecurrentwidget.cpp b/app/editreplacecurrentwidget.cpp index 126f6c9..9cccdb0 100644 --- a/app/editreplacecurrentwidget.cpp +++ b/app/editreplacecurrentwidget.cpp @@ -28,65 +28,63 @@ ReplaceCurrentWidget::ReplaceCurrentWidget(QWidget *parent) : QWidget(parent) { - m_replaceLabel = new QLabel; - m_replaceButton = new QPushButton(tr("&Replace")); - QPushButton *replaceAllButton = new QPushButton(tr("Replace &All")); - QPushButton *dontReplaceButton = new QPushButton(tr("&Don't Replace")); - QPushButton *cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->setIcon(Icon(QLatin1String("dialog-cancel"))); + m_replaceLabel = new QLabel; + m_replaceButton = new QPushButton(tr("&Replace")); + QPushButton *replaceAllButton = new QPushButton(tr("Replace &All")); + QPushButton *dontReplaceButton = new QPushButton(tr("&Don't Replace")); + QPushButton *cancelButton = new QPushButton(tr("&Cancel")); + cancelButton->setIcon(Icon(QLatin1String("dialog-cancel"))); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - QWidget *buttonsWidget = new QWidget; - QHBoxLayout *buttonsLayout = new QHBoxLayout; - buttonsLayout->addWidget(m_replaceButton); - buttonsLayout->addWidget(replaceAllButton); - buttonsLayout->addWidget(dontReplaceButton); - buttonsLayout->addWidget(cancelButton); - buttonsLayout->addStretch(); - buttonsLayout->setMargin(0); - buttonsWidget->setLayout(buttonsLayout); - mainLayout->addWidget(m_replaceLabel); - mainLayout->addWidget(buttonsWidget); + QVBoxLayout *mainLayout = new QVBoxLayout(this); + QWidget *buttonsWidget = new QWidget; + QHBoxLayout *buttonsLayout = new QHBoxLayout; + buttonsLayout->addWidget(m_replaceButton); + buttonsLayout->addWidget(replaceAllButton); + buttonsLayout->addWidget(dontReplaceButton); + buttonsLayout->addWidget(cancelButton); + buttonsLayout->addStretch(); + buttonsLayout->setMargin(0); + buttonsWidget->setLayout(buttonsLayout); + mainLayout->addWidget(m_replaceLabel); + mainLayout->addWidget(buttonsWidget); - setFocusProxy(m_replaceButton); + setFocusProxy(m_replaceButton); - connect(m_replaceButton, SIGNAL(clicked()), this, SIGNAL(replace())); - connect(replaceAllButton, SIGNAL(clicked()), this, SIGNAL(replaceAll())); - connect(dontReplaceButton, SIGNAL(clicked()), this, SLOT(dontReplace())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(hide())); + connect(m_replaceButton, SIGNAL(clicked()), this, SIGNAL(replace())); + connect(replaceAllButton, SIGNAL(clicked()), this, SIGNAL(replaceAll())); + connect(dontReplaceButton, SIGNAL(clicked()), this, SLOT(dontReplace())); + connect(cancelButton, SIGNAL(clicked()), this, SLOT(hide())); } -ReplaceCurrentWidget::~ReplaceCurrentWidget() -{ -} +ReplaceCurrentWidget::~ReplaceCurrentWidget() { } void ReplaceCurrentWidget::setReplacement(const QString &text, const QString &replacement) { - m_replaceLabel->setText(tr("Replace %1 by %2?").arg(text).arg(replacement)); + m_replaceLabel->setText(tr("Replace %1 by %2?").arg(text).arg(replacement)); } void ReplaceCurrentWidget::dontReplace() { - Q_EMIT search(); + Q_EMIT search(); } void ReplaceCurrentWidget::hide() { - setVisible(false); - Q_EMIT hidden(); + setVisible(false); + Q_EMIT hidden(); } void ReplaceCurrentWidget::showEvent(QShowEvent *event) { - m_replaceButton->setFocus(); - QWidget::showEvent(event); + m_replaceButton->setFocus(); + QWidget::showEvent(event); } void ReplaceCurrentWidget::keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Escape) - hide(); - else if (event->key() == Qt::Key_Return) - Q_EMIT replace(); - QWidget::keyPressEvent(event); + if (event->key() == Qt::Key_Escape) + hide(); + else if (event->key() == Qt::Key_Return) + Q_EMIT replace(); + QWidget::keyPressEvent(event); } diff --git a/app/editreplacecurrentwidget.h b/app/editreplacecurrentwidget.h index dae722a..800bd55 100644 --- a/app/editreplacecurrentwidget.h +++ b/app/editreplacecurrentwidget.h @@ -27,32 +27,32 @@ class QPushButton; class ReplaceCurrentWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ReplaceCurrentWidget(QWidget *parent = 0); - ~ReplaceCurrentWidget(); - void setReplacement(const QString &text, const QString &replacement); + explicit ReplaceCurrentWidget(QWidget *parent = 0); + ~ReplaceCurrentWidget(); + void setReplacement(const QString &text, const QString &replacement); Q_SIGNALS: - void search(); - void replace(); - void replaceAll(); - void hidden(); + void search(); + void replace(); + void replaceAll(); + void hidden(); protected: - virtual void showEvent(QShowEvent *event); - virtual void keyPressEvent(QKeyEvent *event); + virtual void showEvent(QShowEvent *event); + virtual void keyPressEvent(QKeyEvent *event); protected Q_SLOTS: - void hide(); + void hide(); private Q_SLOTS: - void dontReplace(); + void dontReplace(); private: - QLabel *m_replaceLabel; - QPushButton *m_replaceButton; + QLabel *m_replaceLabel; + QPushButton *m_replaceButton; }; #endif diff --git a/app/editreplacewidget.cpp b/app/editreplacewidget.cpp index eb771ea..38b4286 100644 --- a/app/editreplacewidget.cpp +++ b/app/editreplacewidget.cpp @@ -21,7 +21,7 @@ #include #ifdef KTIKZ_USE_KDE -#include +# include #endif #include @@ -30,118 +30,116 @@ ReplaceWidget::ReplaceWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); - ui.comboBoxFind->setEditable(true); - ui.comboBoxReplace->setEditable(true); - ui.comboBoxFind->lineEdit()->setClearButtonEnabled(true); - ui.comboBoxReplace->lineEdit()->setClearButtonEnabled(true); - ui.pushButtonClose->setIcon(Icon(QLatin1String("dialog-cancel"))); - ui.pushButtonBackward->setIcon(Icon(QLatin1String("go-up"))); - ui.pushButtonForward->setIcon(Icon(QLatin1String("go-down"))); + ui.setupUi(this); + ui.comboBoxFind->setEditable(true); + ui.comboBoxReplace->setEditable(true); + ui.comboBoxFind->lineEdit()->setClearButtonEnabled(true); + ui.comboBoxReplace->lineEdit()->setClearButtonEnabled(true); + ui.pushButtonClose->setIcon(Icon(QLatin1String("dialog-cancel"))); + ui.pushButtonBackward->setIcon(Icon(QLatin1String("go-up"))); + ui.pushButtonForward->setIcon(Icon(QLatin1String("go-down"))); #ifdef KTIKZ_USE_KDE - // activate completion - KCompletion *completion = ui.comboBoxFind->completionObject(); - connect(ui.comboBoxFind, SIGNAL(returnPressed(QString)), completion, SLOT(addItem(QString))); - completion = ui.comboBoxReplace->completionObject(); - connect(ui.comboBoxReplace, SIGNAL(returnPressed(QString)), completion, SLOT(addItem(QString))); + // activate completion + KCompletion *completion = ui.comboBoxFind->completionObject(); + connect(ui.comboBoxFind, SIGNAL(returnPressed(QString)), completion, SLOT(addItem(QString))); + completion = ui.comboBoxReplace->completionObject(); + connect(ui.comboBoxReplace, SIGNAL(returnPressed(QString)), completion, SLOT(addItem(QString))); #endif - setFocusProxy(ui.comboBoxFind); + setFocusProxy(ui.comboBoxFind); - connect(ui.pushButtonBackward, SIGNAL(clicked()), this, SLOT(setBackward())); - connect(ui.pushButtonForward, SIGNAL(clicked()), this, SLOT(setForward())); - connect(ui.pushButtonFind, SIGNAL(clicked()), this, SLOT(doFind())); - connect(ui.pushButtonReplace, SIGNAL(clicked()), this, SLOT(doReplace())); - connect(ui.pushButtonClose, SIGNAL(clicked()), this, SLOT(hide())); + connect(ui.pushButtonBackward, SIGNAL(clicked()), this, SLOT(setBackward())); + connect(ui.pushButtonForward, SIGNAL(clicked()), this, SLOT(setForward())); + connect(ui.pushButtonFind, SIGNAL(clicked()), this, SLOT(doFind())); + connect(ui.pushButtonReplace, SIGNAL(clicked()), this, SLOT(doReplace())); + connect(ui.pushButtonClose, SIGNAL(clicked()), this, SLOT(hide())); } -ReplaceWidget::~ReplaceWidget() -{ -} +ReplaceWidget::~ReplaceWidget() { } void ReplaceWidget::setBackward() { - ui.pushButtonBackward->setChecked(true); - ui.pushButtonForward->setChecked(false); + ui.pushButtonBackward->setChecked(true); + ui.pushButtonForward->setChecked(false); } void ReplaceWidget::setForward() { - ui.pushButtonBackward->setChecked(false); - ui.pushButtonForward->setChecked(true); + ui.pushButtonBackward->setChecked(false); + ui.pushButtonForward->setChecked(true); } void ReplaceWidget::setForward(bool forward) { - if (forward) - setForward(); - else - setBackward(); + if (forward) + setForward(); + else + setBackward(); } void ReplaceWidget::hide() { - setVisible(false); - Q_EMIT focusEditor(); + setVisible(false); + Q_EMIT focusEditor(); } void ReplaceWidget::doFind() { - const QString currentText = ui.comboBoxFind->currentText(); - if (currentText.isEmpty()) - return; - if (ui.comboBoxFind->findText(currentText) < 0) - ui.comboBoxFind->addItem(currentText); - - QTextDocument::FindFlags flags = 0; - if (ui.checkBoxCaseSensitive->isChecked()) - flags |= QTextDocument::FindCaseSensitively; - if (ui.checkBoxWholeWords->isChecked()) - flags |= QTextDocument::FindWholeWords; - if (!ui.pushButtonForward->isChecked()) - flags |= QTextDocument::FindBackward; - Q_EMIT search(currentText, flags); + const QString currentText = ui.comboBoxFind->currentText(); + if (currentText.isEmpty()) + return; + if (ui.comboBoxFind->findText(currentText) < 0) + ui.comboBoxFind->addItem(currentText); + + QTextDocument::FindFlags flags = 0; + if (ui.checkBoxCaseSensitive->isChecked()) + flags |= QTextDocument::FindCaseSensitively; + if (ui.checkBoxWholeWords->isChecked()) + flags |= QTextDocument::FindWholeWords; + if (!ui.pushButtonForward->isChecked()) + flags |= QTextDocument::FindBackward; + Q_EMIT search(currentText, flags); } void ReplaceWidget::doReplace() { - const QString currentText = ui.comboBoxFind->currentText(); - if (currentText.isEmpty()) - return; - const QString replacementText = ui.comboBoxReplace->currentText(); - if (ui.comboBoxFind->findText(currentText) < 0) - ui.comboBoxFind->addItem(currentText); - if (ui.comboBoxReplace->findText(replacementText) < 0) - ui.comboBoxReplace->addItem(replacementText); - - QTextDocument::FindFlags flags = 0; - if (ui.checkBoxCaseSensitive->isChecked()) - flags |= QTextDocument::FindCaseSensitively; - if (ui.checkBoxWholeWords->isChecked()) - flags |= QTextDocument::FindWholeWords; - if (!ui.pushButtonForward->isChecked()) - flags |= QTextDocument::FindBackward; - Q_EMIT replace(currentText, replacementText, flags); + const QString currentText = ui.comboBoxFind->currentText(); + if (currentText.isEmpty()) + return; + const QString replacementText = ui.comboBoxReplace->currentText(); + if (ui.comboBoxFind->findText(currentText) < 0) + ui.comboBoxFind->addItem(currentText); + if (ui.comboBoxReplace->findText(replacementText) < 0) + ui.comboBoxReplace->addItem(replacementText); + + QTextDocument::FindFlags flags = 0; + if (ui.checkBoxCaseSensitive->isChecked()) + flags |= QTextDocument::FindCaseSensitively; + if (ui.checkBoxWholeWords->isChecked()) + flags |= QTextDocument::FindWholeWords; + if (!ui.pushButtonForward->isChecked()) + flags |= QTextDocument::FindBackward; + Q_EMIT replace(currentText, replacementText, flags); } void ReplaceWidget::setText(const QString &text) { - ui.comboBoxFind->lineEdit()->setText(text); - ui.comboBoxFind->setFocus(); - ui.comboBoxFind->lineEdit()->selectAll(); + ui.comboBoxFind->lineEdit()->setText(text); + ui.comboBoxFind->setFocus(); + ui.comboBoxFind->lineEdit()->selectAll(); } void ReplaceWidget::showEvent(QShowEvent *event) { - ui.comboBoxFind->setFocus(); - QWidget::showEvent(event); + ui.comboBoxFind->setFocus(); + QWidget::showEvent(event); } void ReplaceWidget::keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Escape) - hide(); - else if (event->key() == Qt::Key_Return) - doFind(); - QWidget::keyPressEvent(event); + if (event->key() == Qt::Key_Escape) + hide(); + else if (event->key() == Qt::Key_Return) + doFind(); + QWidget::keyPressEvent(event); } diff --git a/app/editreplacewidget.h b/app/editreplacewidget.h index 022503f..94e84f0 100644 --- a/app/editreplacewidget.h +++ b/app/editreplacewidget.h @@ -24,36 +24,36 @@ class ReplaceWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ReplaceWidget(QWidget *parent = 0); - ~ReplaceWidget(); - void setForward(bool forward); - void setText(const QString &text); + explicit ReplaceWidget(QWidget *parent = 0); + ~ReplaceWidget(); + void setForward(bool forward); + void setText(const QString &text); public Q_SLOTS: - void doFind(); + void doFind(); Q_SIGNALS: - void focusEditor(); - void search(const QString &text, QTextDocument::FindFlags flags); - void replace(const QString &text, const QString &replacement, QTextDocument::FindFlags flags); + void focusEditor(); + void search(const QString &text, QTextDocument::FindFlags flags); + void replace(const QString &text, const QString &replacement, QTextDocument::FindFlags flags); protected: - virtual void showEvent(QShowEvent *event); - virtual void keyPressEvent(QKeyEvent *event); + virtual void showEvent(QShowEvent *event); + virtual void keyPressEvent(QKeyEvent *event); protected Q_SLOTS: - void hide(); + void hide(); private Q_SLOTS: - void setBackward(); - void setForward(); - void doReplace(); + void setBackward(); + void setForward(); + void doReplace(); private: - Ui::ReplaceWidget ui; + Ui::ReplaceWidget ui; }; #endif diff --git a/app/ktikzapplication.cpp b/app/ktikzapplication.cpp index abc5c90..b52c866 100644 --- a/app/ktikzapplication.cpp +++ b/app/ktikzapplication.cpp @@ -26,133 +26,123 @@ #include #include -KtikzApplication::KtikzApplication(int &argc, char **argv) - : QApplication(argc, argv) -{ -} +KtikzApplication::KtikzApplication(int &argc, char **argv) : QApplication(argc, argv) { } void KtikzApplication::init() { - if (isSessionRestored()) - { - QSettings settings; - settings.beginGroup(QLatin1String("Session") + sessionId()); - const int size = settings.beginReadArray(QLatin1String("MainWindowList")); - for (int i = 0; i < size; ++i) - { - settings.setArrayIndex(i); - const QString fileName = settings.value(QLatin1String("CurrentFile")).toString(); - const int lineNumber = settings.value(QLatin1String("LineNumber"), 1).toInt(); - MainWindow *mainWindow = new MainWindow; - mainWindow->show(); - if (!fileName.isEmpty()) - { - mainWindow->loadUrl(QUrl::fromUserInput(fileName)); - mainWindow->setLineNumber(lineNumber); - } - } - settings.endArray(); - settings.remove(QString()); - settings.endGroup(); + if (isSessionRestored()) { + QSettings settings; + settings.beginGroup(QLatin1String("Session") + sessionId()); + const int size = settings.beginReadArray(QLatin1String("MainWindowList")); + for (int i = 0; i < size; ++i) { + settings.setArrayIndex(i); + const QString fileName = settings.value(QLatin1String("CurrentFile")).toString(); + const int lineNumber = settings.value(QLatin1String("LineNumber"), 1).toInt(); + MainWindow *mainWindow = new MainWindow; + mainWindow->show(); + if (!fileName.isEmpty()) { + mainWindow->loadUrl(QUrl::fromUserInput(fileName)); + mainWindow->setLineNumber(lineNumber); + } + } + settings.endArray(); + settings.remove(QString()); + settings.endGroup(); - return; - } + return; + } - MainWindow *mainWindow = new MainWindow; - mainWindow->show(); + MainWindow *mainWindow = new MainWindow; + mainWindow->show(); - QStringList args = arguments(); - for (int i = 1; i < args.size(); ++i) - mainWindow->loadUrl(QUrl::fromUserInput(QFileInfo(args.at(i)).absoluteFilePath())); + QStringList args = arguments(); + for (int i = 1; i < args.size(); ++i) + mainWindow->loadUrl(QUrl::fromUserInput(QFileInfo(args.at(i)).absoluteFilePath())); } #ifdef KTIKZ_USE_KDE QString KtikzApplication::applicationName() { - return QStringLiteral("KtikZ"); + return QStringLiteral("KtikZ"); } #else QString KtikzApplication::applicationName() { - return QStringLiteral("QtikZ"); + return QStringLiteral("QtikZ"); } #endif void KtikzApplication::commitData(QSessionManager &manager) { - if (manager.allowsInteraction()) - { - QList saveDocuments; - QList mainWindowList = MainWindow::mainWindowList(); - // find out which documents to save - for (int i = 0; i < mainWindowList.size(); ++i) - { - if (mainWindowList.at(i)->isDocumentModified()) - { - const QMessageBox::StandardButton ret = QMessageBox::warning(mainWindowList.at(i), - applicationName(), - tr("The document \"%1\" has been modified.\n" - "Do you want to save your changes?").arg(mainWindowList.at(i)->url().fileName()), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, - QMessageBox::Save); - if (ret == QMessageBox::Save) - saveDocuments << i; // store the number of the document that has to be saved - else if (ret == QMessageBox::Cancel) - manager.cancel(); - } - } - manager.release(); // release the manager so that it can handle other programs - // do the actual saving (after releasing the manager, so the manager doesn't have to wait until the saving has finished) - for (int i = 0; i < saveDocuments.size(); ++i) - { - if (!mainWindowList.at(saveDocuments.at(i))->save()) - manager.cancel(); - } - } - else - { -// TODO save unsaved documents to a temporary file - } + if (manager.allowsInteraction()) { + QList saveDocuments; + QList mainWindowList = MainWindow::mainWindowList(); + // find out which documents to save + for (int i = 0; i < mainWindowList.size(); ++i) { + if (mainWindowList.at(i)->isDocumentModified()) { + const QMessageBox::StandardButton ret = QMessageBox::warning( + mainWindowList.at(i), applicationName(), + tr("The document \"%1\" has been modified.\n" + "Do you want to save your changes?") + .arg(mainWindowList.at(i)->url().fileName()), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, + QMessageBox::Save); + if (ret == QMessageBox::Save) + saveDocuments << i; // store the number of the document that has to be saved + else if (ret == QMessageBox::Cancel) + manager.cancel(); + } + } + manager.release(); // release the manager so that it can handle other programs + // do the actual saving (after releasing the manager, so the manager doesn't have to wait + // until the saving has finished) + for (int i = 0; i < saveDocuments.size(); ++i) { + if (!mainWindowList.at(saveDocuments.at(i))->save()) + manager.cancel(); + } + } else { + // TODO save unsaved documents to a temporary file + } } void KtikzApplication::saveState(QSessionManager &manager) { - QList mainWindowList = MainWindow::mainWindowList(); - if (mainWindowList.size() == 0) - return; + QList mainWindowList = MainWindow::mainWindowList(); + if (mainWindowList.size() == 0) + return; - // in X11 the session manager calls saveState() also on startup, - // we don't want to save anything at startup, so we define a - // discard command (in main.cpp) which cleans up the unnecessary - // session information - QStringList discard = QStringList(applicationFilePath()); - discard << QLatin1String("--discard") << sessionId(); - manager.setDiscardCommand(discard); // this lets xsm hang, but it works in real session management in KDE Plasma + // in X11 the session manager calls saveState() also on startup, + // we don't want to save anything at startup, so we define a + // discard command (in main.cpp) which cleans up the unnecessary + // session information + QStringList discard = QStringList(applicationFilePath()); + discard << QLatin1String("--discard") << sessionId(); + manager.setDiscardCommand( + discard); // this lets xsm hang, but it works in real session management in KDE Plasma - QSettings settings; - settings.beginGroup(QLatin1String("Session") + sessionId()); - settings.beginWriteArray(QLatin1String("MainWindowList")); - for (int i = 0; i < mainWindowList.size(); ++i) - { - settings.setArrayIndex(i); - settings.setValue(QLatin1String("CurrentFile"), mainWindowList.at(i)->url().path()); - settings.setValue(QLatin1String("LineNumber"), mainWindowList.at(i)->lineNumber()); - } - settings.endArray(); - settings.endGroup(); + QSettings settings; + settings.beginGroup(QLatin1String("Session") + sessionId()); + settings.beginWriteArray(QLatin1String("MainWindowList")); + for (int i = 0; i < mainWindowList.size(); ++i) { + settings.setArrayIndex(i); + settings.setValue(QLatin1String("CurrentFile"), mainWindowList.at(i)->url().path()); + settings.setValue(QLatin1String("LineNumber"), mainWindowList.at(i)->lineNumber()); + } + settings.endArray(); + settings.endGroup(); } KtikzApplication::~KtikzApplication() { - // don't delete the MainWindows here because they are already deleted on - // close, however: - // the MainWindows are not deleted by the session manager when the session - // closes, therefore we explicitly delete them here so that the temporary - // files generated by them get deleted, note that we cannot delete them - // in commitData() or saveState() because both need access to them and it - // is not specified which is executed first, furthermore I see no other - // way of deleting them when KTIKZ_USE_KDE is defined - QList mainWindowList = MainWindow::mainWindowList(); - while (!mainWindowList.isEmpty()) - delete mainWindowList.takeFirst(); + // don't delete the MainWindows here because they are already deleted on + // close, however: + // the MainWindows are not deleted by the session manager when the session + // closes, therefore we explicitly delete them here so that the temporary + // files generated by them get deleted, note that we cannot delete them + // in commitData() or saveState() because both need access to them and it + // is not specified which is executed first, furthermore I see no other + // way of deleting them when KTIKZ_USE_KDE is defined + QList mainWindowList = MainWindow::mainWindowList(); + while (!mainWindowList.isEmpty()) + delete mainWindowList.takeFirst(); } diff --git a/app/ktikzapplication.h b/app/ktikzapplication.h index b0a15e6..f7e5ced 100644 --- a/app/ktikzapplication.h +++ b/app/ktikzapplication.h @@ -24,18 +24,18 @@ class KtikzApplication : public QApplication { - Q_OBJECT + Q_OBJECT public: - KtikzApplication(int &argc, char **argv); - virtual ~KtikzApplication(); + KtikzApplication(int &argc, char **argv); + virtual ~KtikzApplication(); - void init(); - static QString applicationName(); + void init(); + static QString applicationName(); protected: - void commitData(QSessionManager &manager); - void saveState(QSessionManager &manager); + void commitData(QSessionManager &manager); + void saveState(QSessionManager &manager); }; #endif diff --git a/app/linenumberwidget.cpp b/app/linenumberwidget.cpp index f770f3f..107fa59 100644 --- a/app/linenumberwidget.cpp +++ b/app/linenumberwidget.cpp @@ -24,89 +24,91 @@ #include "tikzeditor.h" -LineNumberWidget::LineNumberWidget(TikzEditor *editor) - : QWidget(editor), m_editor(editor) +LineNumberWidget::LineNumberWidget(TikzEditor *editor) : QWidget(editor), m_editor(editor) { - setAutoFillBackground(true); - - QPalette p(palette()); - const QPalette standardPalette(p); // const QPalette standardPalette(QApplication::style()->standardPalette()); is slow, since we are in the constructor palette() == QApplication::palette() - const QColor windowColor(standardPalette.color(QPalette::Normal, QPalette::Window)); - p.setColor(backgroundRole(), windowColor.lighter(102)); - setPalette(p); - - m_highlightColor = QColor(standardPalette.color(QPalette::Normal, QPalette::Highlight)); - m_highlightBrush = QBrush(m_highlightColor); - m_highlightPen = QPen(m_highlightColor); - m_highlightPen.setStyle(Qt::SolidLine); - m_highlightedTextPen = QPen(standardPalette.color(QPalette::Normal, QPalette::HighlightedText)); - - setToolTip(tr("Click to add or remove a bookmark")); + setAutoFillBackground(true); + + QPalette p(palette()); + const QPalette standardPalette( + p); // const QPalette standardPalette(QApplication::style()->standardPalette()); is + // slow, since we are in the constructor palette() == QApplication::palette() + const QColor windowColor(standardPalette.color(QPalette::Normal, QPalette::Window)); + p.setColor(backgroundRole(), windowColor.lighter(102)); + setPalette(p); + + m_highlightColor = QColor(standardPalette.color(QPalette::Normal, QPalette::Highlight)); + m_highlightBrush = QBrush(m_highlightColor); + m_highlightPen = QPen(m_highlightColor); + m_highlightPen.setStyle(Qt::SolidLine); + m_highlightedTextPen = QPen(standardPalette.color(QPalette::Normal, QPalette::HighlightedText)); + + setToolTip(tr("Click to add or remove a bookmark")); } QSize LineNumberWidget::sizeHint() const { - return QSize(m_editor->lineNumberAreaWidth(), 0); + return QSize(m_editor->lineNumberAreaWidth(), 0); } void LineNumberWidget::paintEvent(QPaintEvent *event) { - QPainter painter(this); - - const QFontMetrics fm = m_editor->fontMetrics(); - - // draw separator between line number area and text editor - painter.setPen(m_highlightPen); - painter.drawLine(width() - 2, 0, width() - 2, height()); - - QTextBlock block = m_editor->firstVisibleBlock(); - int lineNumber = block.blockNumber() + 1; - int top = (int) m_editor->blockBoundingGeometry(block).translated(m_editor->contentOffset()).top(); - int lineHeight = m_editor->blockBoundingRect(block).height(); - int bottom = top + lineHeight; - - QList userBookmarks = m_editor->userBookmarks(); - while (block.isValid() && top <= event->rect().bottom()) - { - if (bottom >= event->rect().top()) - { - for (int i = 0; i < userBookmarks.length(); ++i) - { - if (userBookmarks.at(i) == lineNumber) - { - painter.fillRect(2, top, fm.width(QLatin1Char('B')) + 4, lineHeight, m_highlightBrush); - painter.setPen(m_highlightedTextPen); - painter.drawText(4, top, width() - 4, lineHeight, Qt::AlignLeft | Qt::AlignTop, QLatin1String("B")); - painter.setPen(m_highlightPen); -// update(0, top, width(), lineHeight); // make sure the bookmark is visible even when the line is wrapped - break; - } - } - painter.drawText(0, top, width() - 4, lineHeight, Qt::AlignRight | Qt::AlignTop, QString::number(lineNumber)); - } - - block = block.next(); - top = bottom; - lineHeight = m_editor->blockBoundingRect(block).height(); - bottom += lineHeight; - ++lineNumber; - } - painter.end(); + QPainter painter(this); + + const QFontMetrics fm = m_editor->fontMetrics(); + + // draw separator between line number area and text editor + painter.setPen(m_highlightPen); + painter.drawLine(width() - 2, 0, width() - 2, height()); + + QTextBlock block = m_editor->firstVisibleBlock(); + int lineNumber = block.blockNumber() + 1; + int top = + (int)m_editor->blockBoundingGeometry(block).translated(m_editor->contentOffset()).top(); + int lineHeight = m_editor->blockBoundingRect(block).height(); + int bottom = top + lineHeight; + + QList userBookmarks = m_editor->userBookmarks(); + while (block.isValid() && top <= event->rect().bottom()) { + if (bottom >= event->rect().top()) { + for (int i = 0; i < userBookmarks.length(); ++i) { + if (userBookmarks.at(i) == lineNumber) { + painter.fillRect(2, top, fm.width(QLatin1Char('B')) + 4, lineHeight, + m_highlightBrush); + painter.setPen(m_highlightedTextPen); + painter.drawText(4, top, width() - 4, lineHeight, Qt::AlignLeft | Qt::AlignTop, + QLatin1String("B")); + painter.setPen(m_highlightPen); + // update(0, top, width(), lineHeight); // make + //sure the bookmark is visible even when the line is wrapped + break; + } + } + painter.drawText(0, top, width() - 4, lineHeight, Qt::AlignRight | Qt::AlignTop, + QString::number(lineNumber)); + } + + block = block.next(); + top = bottom; + lineHeight = m_editor->blockBoundingRect(block).height(); + bottom += lineHeight; + ++lineNumber; + } + painter.end(); } void LineNumberWidget::mousePressEvent(QMouseEvent *event) { - event->accept(); - const QPoint p = m_editor->viewport()->mapFromGlobal(event->globalPos()); - const int lineNumber = m_editor->cursorForPosition(p).blockNumber() + 1; - if (lineNumber <= 0) - return; - - m_editor->toggleUserBookmark(lineNumber); - update(); + event->accept(); + const QPoint p = m_editor->viewport()->mapFromGlobal(event->globalPos()); + const int lineNumber = m_editor->cursorForPosition(p).blockNumber() + 1; + if (lineNumber <= 0) + return; + + m_editor->toggleUserBookmark(lineNumber); + update(); } -void LineNumberWidget::mouseReleaseEvent(QMouseEvent*) +void LineNumberWidget::mouseReleaseEvent(QMouseEvent *) { - m_editor->setFocus(); + m_editor->setFocus(); } diff --git a/app/linenumberwidget.h b/app/linenumberwidget.h index cd769d3..a6284f7 100644 --- a/app/linenumberwidget.h +++ b/app/linenumberwidget.h @@ -26,22 +26,22 @@ class TikzEditor; class LineNumberWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit LineNumberWidget(TikzEditor *editor); - QSize sizeHint() const; + explicit LineNumberWidget(TikzEditor *editor); + QSize sizeHint() const; protected: - virtual void paintEvent(QPaintEvent *event); - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent*); + virtual void paintEvent(QPaintEvent *event); + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *); private: - TikzEditor* m_editor; - QColor m_highlightColor; - QBrush m_highlightBrush; - QPen m_highlightPen; - QPen m_highlightedTextPen; + TikzEditor *m_editor; + QColor m_highlightColor; + QBrush m_highlightBrush; + QPen m_highlightPen; + QPen m_highlightedTextPen; }; #endif // LINENUMBERWIDGET_H diff --git a/app/loghighlighter.cpp b/app/loghighlighter.cpp index 6b3bbf8..93f2326 100644 --- a/app/loghighlighter.cpp +++ b/app/loghighlighter.cpp @@ -20,74 +20,72 @@ #include "loghighlighter.h" -LogHighlighter::LogHighlighter(QTextDocument *parent) - : QSyntaxHighlighter(parent) +LogHighlighter::LogHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { - LogHighlightingRule rule; + LogHighlightingRule rule; - QTextCharFormat keywordFormat; - keywordFormat.setForeground(Qt::red); - keywordFormat.setFontWeight(QFont::Bold); - QStringList keywordPatterns; - keywordPatterns << QLatin1String("\\S*:\\d+:.*$") << QLatin1String("Undefined control sequence") - << QLatin1String("LaTeX Warning:") << QLatin1String("LaTeX Error:") << QLatin1String("Runaway argument?") - << QLatin1String("Missing character: .*!") << QLatin1String("Error:") - << tr("Error:") << tr("Warning:") // error msg created by TikzPreviewGenerator - << QLatin1String("^\\[.*\\] Line \\d+: .*") // error msg created by TikzPreviewGenerator::getParsedLogText() - << tr("This program will not work!"); - Q_FOREACH (const QString &pattern, keywordPatterns) - { - rule.pattern = QRegExp(pattern); - rule.format = keywordFormat; - m_highlightingRules.append(rule); - } + QTextCharFormat keywordFormat; + keywordFormat.setForeground(Qt::red); + keywordFormat.setFontWeight(QFont::Bold); + QStringList keywordPatterns; + keywordPatterns + << QLatin1String("\\S*:\\d+:.*$") << QLatin1String("Undefined control sequence") + << QLatin1String("LaTeX Warning:") << QLatin1String("LaTeX Error:") + << QLatin1String("Runaway argument?") << QLatin1String("Missing character: .*!") + << QLatin1String("Error:") << tr("Error:") + << tr("Warning:") // error msg created by TikzPreviewGenerator + << QLatin1String("^\\[.*\\] Line \\d+: .*") // error msg created by + // TikzPreviewGenerator::getParsedLogText() + << tr("This program will not work!"); + Q_FOREACH (const QString &pattern, keywordPatterns) { + rule.pattern = QRegExp(pattern); + rule.format = keywordFormat; + m_highlightingRules.append(rule); + } - QTextCharFormat commandFormat; - commandFormat.setForeground(Qt::darkBlue); - commandFormat.setFontWeight(QFont::Bold); - rule.pattern = QRegExp(QLatin1String("^\\[[^\\]\\d][^\\]]*\\]")); - rule.format = commandFormat; - m_highlightingRules.append(rule); + QTextCharFormat commandFormat; + commandFormat.setForeground(Qt::darkBlue); + commandFormat.setFontWeight(QFont::Bold); + rule.pattern = QRegExp(QLatin1String("^\\[[^\\]\\d][^\\]]*\\]")); + rule.format = commandFormat; + m_highlightingRules.append(rule); - m_statisticsFormat.setForeground(Qt::darkGray); -// m_statisticsFormat.setFontPointSize(5.0); - m_statisticsStartExpression = QLatin1String("Here is how much of TeX's memory you used:"); + m_statisticsFormat.setForeground(Qt::darkGray); + // m_statisticsFormat.setFontPointSize(5.0); + m_statisticsStartExpression = QLatin1String("Here is how much of TeX's memory you used:"); } -LogHighlighter::~LogHighlighter() -{ -} +LogHighlighter::~LogHighlighter() { } void LogHighlighter::highlightBlock(const QString &text) { - // Try each highlighting pattern and apply formatting if it matches - Q_FOREACH (const LogHighlightingRule &rule, m_highlightingRules) - { -// const QRegExp expression(rule.pattern); -// int index = text.indexOf(expression); - QRegExp expression(rule.pattern); - int index = expression.indexIn(text); - while (index >= 0) - { - const int length = expression.matchedLength(); - setFormat(index, length, rule.format); -// index = text.indexOf(expression, index + length); - index = expression.indexIn(text, index + length); - } - } + // Try each highlighting pattern and apply formatting if it matches + Q_FOREACH (const LogHighlightingRule &rule, m_highlightingRules) { + // const QRegExp expression(rule.pattern); + // int index = text.indexOf(expression); + QRegExp expression(rule.pattern); + int index = expression.indexIn(text); + while (index >= 0) { + const int length = expression.matchedLength(); + setFormat(index, length, rule.format); + // index = text.indexOf(expression, index + length); + index = expression.indexIn(text, index + length); + } + } - // Highlight statistics (at the end of the log) - setCurrentBlockState(0); // The current block state tracks multiline formatting - int startIndex = text.indexOf(m_statisticsStartExpression); // Index to start highlighting statistics (if any) - if (previousBlockState() == 1) // The previous block ended within statistics - startIndex = 0; // Continue highlighting statistics + // Highlight statistics (at the end of the log) + setCurrentBlockState(0); // The current block state tracks multiline formatting + int startIndex = text.indexOf( + m_statisticsStartExpression); // Index to start highlighting statistics (if any) + if (previousBlockState() == 1) // The previous block ended within statistics + startIndex = 0; // Continue highlighting statistics - if (startIndex >= 0) - { - const int endIndex = text.size() - 1; - const int statisticsLength = endIndex - startIndex + 1; - setFormat(startIndex, statisticsLength, m_statisticsFormat); - // Make the next invocation of this routine aware that it should continue highlighting in statistics format - setCurrentBlockState(1); - } + if (startIndex >= 0) { + const int endIndex = text.size() - 1; + const int statisticsLength = endIndex - startIndex + 1; + setFormat(startIndex, statisticsLength, m_statisticsFormat); + // Make the next invocation of this routine aware that it should continue highlighting in + // statistics format + setCurrentBlockState(1); + } } diff --git a/app/loghighlighter.h b/app/loghighlighter.h index a3c7b70..d13cae2 100644 --- a/app/loghighlighter.h +++ b/app/loghighlighter.h @@ -29,30 +29,30 @@ */ class LogHighlighter : public QSyntaxHighlighter { - Q_OBJECT + Q_OBJECT public: - explicit LogHighlighter(QTextDocument *parent = 0); - virtual ~LogHighlighter(); + explicit LogHighlighter(QTextDocument *parent = 0); + virtual ~LogHighlighter(); protected: - /** Implements QSyntaxHighlighter::highlightBlock() - * @see QSyntaxHighlighter::highlightBlock() - */ - void highlightBlock(const QString &text); + /** Implements QSyntaxHighlighter::highlightBlock() + * @see QSyntaxHighlighter::highlightBlock() + */ + void highlightBlock(const QString &text); private: - struct LogHighlightingRule - { - QRegExp pattern; /// The pattern to match for formatting - QTextCharFormat format; /// The style of the formatting - }; - /// All highlighting rules with their formatting for easy iteration - QVector m_highlightingRules; - /// The start of the statistics output by LaTeX - QString m_statisticsStartExpression; - /// The highlighting format for LaTeX statistics - QTextCharFormat m_statisticsFormat; + struct LogHighlightingRule + { + QRegExp pattern; /// The pattern to match for formatting + QTextCharFormat format; /// The style of the formatting + }; + /// All highlighting rules with their formatting for easy iteration + QVector m_highlightingRules; + /// The start of the statistics output by LaTeX + QString m_statisticsStartExpression; + /// The highlighting format for LaTeX statistics + QTextCharFormat m_statisticsFormat; }; #endif diff --git a/app/logtextedit.cpp b/app/logtextedit.cpp index 5191fa9..c1ab3e5 100644 --- a/app/logtextedit.cpp +++ b/app/logtextedit.cpp @@ -23,52 +23,50 @@ LogTextEdit::LogTextEdit(QWidget *parent) : QTextEdit(parent) { - m_logHighlighter = new LogHighlighter(document()); - setReadOnly(true); + m_logHighlighter = new LogHighlighter(document()); + setReadOnly(true); } LogTextEdit::~LogTextEdit() { - m_logHighlighter->deleteLater(); + m_logHighlighter->deleteLater(); } QSize LogTextEdit::sizeHint() const { - return QSize(300, 90); + return QSize(300, 90); } void LogTextEdit::updateLog(const QString &logText) { - setPlainText(logText); + setPlainText(logText); } void LogTextEdit::updateLog(const QString &logText, bool runFailed) { - setPlainText(logText); - setLogPalette(runFailed); + setPlainText(logText); + setLogPalette(runFailed); } void LogTextEdit::appendLog(const QString &logText) { - setPlainText(toPlainText() + logText); + setPlainText(toPlainText() + logText); } void LogTextEdit::appendLog(const QString &logText, bool runFailed) { - setPlainText(toPlainText() + logText); - setLogPalette(runFailed); + setPlainText(toPlainText() + logText); + setLogPalette(runFailed); } void LogTextEdit::setLogPalette(bool runFailed) { - moveCursor(QTextCursor::End); - if (runFailed) - { - QPalette failedPalette(QApplication::palette()); - failedPalette.setColor(QPalette::Background, QColor(255, 102, 102)); - setAutoFillBackground(true); - setPalette(failedPalette); - } - else - setPalette(QApplication::palette()); + moveCursor(QTextCursor::End); + if (runFailed) { + QPalette failedPalette(QApplication::palette()); + failedPalette.setColor(QPalette::Background, QColor(255, 102, 102)); + setAutoFillBackground(true); + setPalette(failedPalette); + } else + setPalette(QApplication::palette()); } diff --git a/app/logtextedit.h b/app/logtextedit.h index 2b304f9..661e2a9 100644 --- a/app/logtextedit.h +++ b/app/logtextedit.h @@ -26,22 +26,22 @@ class QSyntaxHighlighter; class LogTextEdit : public QTextEdit { - Q_OBJECT + Q_OBJECT public: - explicit LogTextEdit(QWidget *parent = 0); - ~LogTextEdit(); - virtual QSize sizeHint() const; + explicit LogTextEdit(QWidget *parent = 0); + ~LogTextEdit(); + virtual QSize sizeHint() const; public Q_SLOTS: - void updateLog(const QString &logText); - void updateLog(const QString &logText, bool runFailed); - void appendLog(const QString &logText); - void appendLog(const QString &logText, bool runFailed); + void updateLog(const QString &logText); + void updateLog(const QString &logText, bool runFailed); + void appendLog(const QString &logText); + void appendLog(const QString &logText, bool runFailed); private: - void setLogPalette(bool runFailed); - QSyntaxHighlighter *m_logHighlighter; + void setLogPalette(bool runFailed); + QSyntaxHighlighter *m_logHighlighter; }; #endif diff --git a/app/main.cpp b/app/main.cpp index 8661be7..378feb7 100644 --- a/app/main.cpp +++ b/app/main.cpp @@ -19,10 +19,10 @@ ***************************************************************************/ #ifdef KTIKZ_USE_KDE -#include -#include +# include +# include #else -#include +# include #endif #include @@ -38,136 +38,150 @@ #include "ktikzapplication.h" // add copyright notice to the *.ts files; this string is not used anywhere else -static struct { const char *source; const char *comment; } copyrightString = QT_TRANSLATE_NOOP3("__Copyright__", - "The original English text is copyrighted by the authors of the source " - "files where the strings come from. This file is distributed under the " - "same license as the KtikZ package. The translations in this file are " - "copyrighted as follows.", - "Translators: don't translate this, but put in the \"translation\" " - "a copyright notice of the form \"This file was translated by . " - "Copyright (C) .\" in which you fill in the year(s) of " - "translation and your name."); +static struct +{ + const char *source; + const char *comment; +} copyrightString = + QT_TRANSLATE_NOOP3("__Copyright__", + "The original English text is copyrighted by the authors of the source " + "files where the strings come from. This file is distributed under the " + "same license as the KtikZ package. The translations in this file are " + "copyrighted as follows.", + "Translators: don't translate this, but put in the \"translation\" " + "a copyright notice of the form \"This file was translated by . " + "Copyright (C) .\" in which you fill in the year(s) of " + "translation and your name."); static void debugOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { - // qDebug() and qWarning() only show messages when in debug mode - QByteArray localMsg = msg.toLocal8Bit(); - switch (type) - { - case QtDebugMsg: + // qDebug() and qWarning() only show messages when in debug mode + QByteArray localMsg = msg.toLocal8Bit(); + switch (type) { + case QtDebugMsg: case QtInfoMsg: case QtWarningMsg: #ifndef QT_NO_DEBUG - fprintf(stderr, "%s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); + fprintf(stderr, "%s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, + context.function); #endif - break; - case QtCriticalMsg: - fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); - break; - case QtFatalMsg: - fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function); - abort(); - } + break; + case QtCriticalMsg: + fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, + context.line, context.function); + break; + case QtFatalMsg: + fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, + context.function); + abort(); + } } -static bool findTranslator(QTranslator *translator, const QString &transName, const QString &transDir) +static bool findTranslator(QTranslator *translator, const QString &transName, + const QString &transDir) { - const QString qmFile = transName + QLatin1String(".qm"); - const QFileInfo fi(QDir(transDir), qmFile); - if (fi.exists()) - return translator->load(qmFile, transDir); - return false; + const QString qmFile = transName + QLatin1String(".qm"); + const QFileInfo fi(QDir(transDir), qmFile); + if (fi.exists()) + return translator->load(qmFile, transDir); + return false; } -static void createTranslator(QTranslator *translator, const QString &transName, const QString &transDir) +static void createTranslator(QTranslator *translator, const QString &transName, + const QString &transDir) { - const QString locale = QString(QLocale::system().name()); - const QString localeShort = locale.left(2).toLower(); + const QString locale = QString(QLocale::system().name()); + const QString localeShort = locale.left(2).toLower(); - const QStringList transDirs = QStringList() << transDir + const QStringList transDirs = QStringList() + << transDir #ifdef KTIKZ_TRANSLATIONS_INSTALL_DIR - << QDir(QLatin1String(KTIKZ_TRANSLATIONS_INSTALL_DIR)).absolutePath() // set during compilation + << QDir(QLatin1String(KTIKZ_TRANSLATIONS_INSTALL_DIR)) + .absolutePath() // set during compilation #endif // KTIKZ_TRANSLATIONS_INSTALL_DIR - << QString(); // working dir - - for (int i = 0; i < transDirs.size(); ++i) - { - if (findTranslator(translator, transName + QLatin1Char('_') + locale, transDirs.at(i))) - return; - if (findTranslator(translator, transName + QLatin1Char('_') + localeShort, transDirs.at(i))) - return; - } + << QString(); // working dir + + for (int i = 0; i < transDirs.size(); ++i) { + if (findTranslator(translator, transName + QLatin1Char('_') + locale, transDirs.at(i))) + return; + if (findTranslator(translator, transName + QLatin1Char('_') + localeShort, transDirs.at(i))) + return; + } } int main(int argc, char **argv) { -//QTime t = QTime::currentTime(); - Q_UNUSED(copyrightString); + // QTime t = QTime::currentTime(); + Q_UNUSED(copyrightString); - qInstallMessageHandler(debugOutput); + qInstallMessageHandler(debugOutput); #ifndef KTIKZ_USE_KDE - // discard session (X11 calls QApplication::saveState() also when the app - // has been started, but then also calls QSessionManager::discardCommand() - // which we define as below in order to remove unnecessary session - // information) - if (argc == 3 && !strcmp(argv[1], "--discard")) - { - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - settings.remove(QLatin1String("Session") + QLatin1String(argv[2])); // argv[2] contains the session id - settings.sync(); - return 0; - } + // discard session (X11 calls QApplication::saveState() also when the app + // has been started, but then also calls QSessionManager::discardCommand() + // which we define as below in order to remove unnecessary session + // information) + if (argc == 3 && !strcmp(argv[1], "--discard")) { + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + settings.remove(QLatin1String("Session") + + QLatin1String(argv[2])); // argv[2] contains the session id + settings.sync(); + return 0; + } #endif #ifdef KTIKZ_USE_KDE - Q_INIT_RESOURCE(ktikz); + Q_INIT_RESOURCE(ktikz); #else - Q_INIT_RESOURCE(qtikz); + Q_INIT_RESOURCE(qtikz); #endif - KtikzApplication app(argc, argv); // slow + KtikzApplication app(argc, argv); // slow #ifdef KTIKZ_USE_KDE - Q_INIT_RESOURCE(ktikz); - - KAboutData aboutData(QStringLiteral("ktikz"),i18n("KtikZ"), APPVERSION); - aboutData.setShortDescription(i18n("A TikZ Editor")); - aboutData.setLicense(KAboutLicense::GPL_V2); - aboutData.setCopyrightStatement(i18n("Copyright 2007-2017 Florian Hackenberger, Glad Deschrijver, Joao Carreira")); - aboutData.setOtherText(i18n("This is a program for creating TikZ (from the LaTeX pgf package) diagrams.")); - aboutData.setBugAddress("jfmcarreira@gmail.com"); - aboutData.addAuthor(i18n("Florian Hackenberger"), i18n("Maintainer"), "florian@hackenberger.at"); - aboutData.addAuthor(i18n("Glad Deschrijver"), i18n("Developer"), "glad.deschrijver@gmail.com"); - aboutData.addAuthor(i18n("Joao Carreira"), i18n("Maintainer"), "jfmcarreira@gmail.com"); - - QCommandLineParser parser; - aboutData.setupCommandLine(&parser); - KAboutData::setApplicationData(aboutData); - parser.addVersionOption(); - parser.addHelpOption(); - parser.addPositionalArgument(QLatin1String("[URL]"), i18n("TikZ document to open")); - parser.process(app); // PORTING SCRIPT: move this to after any parser.addOption - aboutData.processCommandLine(&parser); + Q_INIT_RESOURCE(ktikz); + + KAboutData aboutData(QStringLiteral("ktikz"), i18n("KtikZ"), APPVERSION); + aboutData.setShortDescription(i18n("A TikZ Editor")); + aboutData.setLicense(KAboutLicense::GPL_V2); + aboutData.setCopyrightStatement( + i18n("Copyright 2007-2017 Florian Hackenberger, Glad Deschrijver, Joao Carreira")); + aboutData.setOtherText( + i18n("This is a program for creating TikZ (from the LaTeX pgf package) diagrams.")); + aboutData.setBugAddress("jfmcarreira@gmail.com"); + aboutData.addAuthor(i18n("Florian Hackenberger"), i18n("Maintainer"), + "florian@hackenberger.at"); + aboutData.addAuthor(i18n("Glad Deschrijver"), i18n("Developer"), "glad.deschrijver@gmail.com"); + aboutData.addAuthor(i18n("Joao Carreira"), i18n("Maintainer"), "jfmcarreira@gmail.com"); + + QCommandLineParser parser; + aboutData.setupCommandLine(&parser); + KAboutData::setApplicationData(aboutData); + parser.addVersionOption(); + parser.addHelpOption(); + parser.addPositionalArgument(QLatin1String("[URL]"), i18n("TikZ document to open")); + parser.process(app); // PORTING SCRIPT: move this to after any parser.addOption + aboutData.processCommandLine(&parser); #endif - - QCoreApplication::setOrganizationName(QString::fromLocal8Bit(ORGNAME)); + QCoreApplication::setOrganizationName(QString::fromLocal8Bit(ORGNAME)); #ifndef KTIKZ_USE_KDE - QCoreApplication::setApplicationName(QString::fromLocal8Bit(APPNAME)); - QCoreApplication::setApplicationVersion(QString::fromLocal8Bit(APPVERSION)); + QCoreApplication::setApplicationName(QString::fromLocal8Bit(APPNAME)); + QCoreApplication::setApplicationVersion(QString::fromLocal8Bit(APPVERSION)); #endif - const QString translationsDirPath = QString::fromLocal8Bit(qgetenv("KTIKZ_TRANSLATIONS_DIR").constData()); - QTranslator qtTranslator; - QTranslator qtikzTranslator; - createTranslator(&qtTranslator, QLatin1String("qt"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); - createTranslator(&qtikzTranslator, QLatin1String("qtikz"), translationsDirPath); - app.installTranslator(&qtTranslator); - app.installTranslator(&qtikzTranslator); - - app.init(); -//qCritical() << t.msecsTo(QTime::currentTime()); - return app.exec(); + const QString translationsDirPath = + QString::fromLocal8Bit(qgetenv("KTIKZ_TRANSLATIONS_DIR").constData()); + QTranslator qtTranslator; + QTranslator qtikzTranslator; + createTranslator(&qtTranslator, QLatin1String("qt"), + QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + createTranslator(&qtikzTranslator, QLatin1String("qtikz"), translationsDirPath); + app.installTranslator(&qtTranslator); + app.installTranslator(&qtikzTranslator); + + app.init(); + // qCritical() << t.msecsTo(QTime::currentTime()); + return app.exec(); } diff --git a/app/mainwindow.cpp b/app/mainwindow.cpp index 580952f..a350561 100644 --- a/app/mainwindow.cpp +++ b/app/mainwindow.cpp @@ -20,19 +20,19 @@ * along with this program; if not, see . * ***************************************************************************/ -//#include +// #include #include "mainwindow.h" #ifdef KTIKZ_USE_KDE -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include #else -#include -#include "aboutdialog.h" -#include "assistantcontroller.h" +# include +# include "aboutdialog.h" +# include "assistantcontroller.h" #endif #include @@ -76,441 +76,449 @@ #include "../common/utils/url.h" #ifdef KTIKZ_USE_KTEXTEDITOR -#include "tikzktexteditorview.h" +# include "tikzktexteditorview.h" #endif -QList MainWindow::s_mainWindowList; +QList MainWindow::s_mainWindowList; MainWindow::MainWindow() { -//QTime t = QTime::currentTime(); +// QTime t = QTime::currentTime(); #ifndef KTIKZ_USE_KDE - m_aboutDialog = 0; - m_assistantController = 0; + m_aboutDialog = 0; + m_assistantController = 0; #endif - m_configDialog = 0; - m_isModifiedExternally = false; - m_insertAction = 0; + m_configDialog = 0; + m_isModifiedExternally = false; + m_insertAction = 0; - s_mainWindowList.append(this); + s_mainWindowList.append(this); #ifndef KTIKZ_USE_KDE - QStringList themeSearchPaths; - themeSearchPaths << QDir::homePath() + QLatin1String("/.local/share/icons/"); - themeSearchPaths << QIcon::themeSearchPaths(); - QIcon::setThemeSearchPaths(themeSearchPaths); + QStringList themeSearchPaths; + themeSearchPaths << QDir::homePath() + QLatin1String("/.local/share/icons/"); + themeSearchPaths << QIcon::themeSearchPaths(); + QIcon::setThemeSearchPaths(themeSearchPaths); #endif - setAttribute(Qt::WA_DeleteOnClose); + setAttribute(Qt::WA_DeleteOnClose); #ifdef KTIKZ_USE_KDE - setObjectName(QLatin1String("ktikz#")); - setWindowIcon(QIcon::fromTheme(QLatin1String("ktikz"))); - Action::setActionCollection(actionCollection()); + setObjectName(QLatin1String("ktikz#")); + setWindowIcon(QIcon::fromTheme(QLatin1String("ktikz"))); + Action::setActionCollection(actionCollection()); #else - setObjectName(QLatin1String("qtikz#") + QString::number(s_mainWindowList.size())); - setWindowIcon(QIcon(QLatin1String(":/icons/qtikz-22.png"))); + setObjectName(QLatin1String("qtikz#") + QString::number(s_mainWindowList.size())); + setWindowIcon(QIcon(QLatin1String(":/icons/qtikz-22.png"))); #endif - setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); - setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); -//qCritical() << t.msecsTo(QTime::currentTime()); - m_tikzPreviewController = new TikzPreviewController(this); -//qCritical() << "TikzPreviewController" << t.msecsTo(QTime::currentTime()); + // qCritical() << t.msecsTo(QTime::currentTime()); + m_tikzPreviewController = new TikzPreviewController(this); + // qCritical() << "TikzPreviewController" << t.msecsTo(QTime::currentTime()); - m_useKTextEditor = false; + m_useKTextEditor = false; #ifdef KTIKZ_USE_KTEXTEDITOR - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - m_useKTextEditor = settings.value(QLatin1String("EditorWidget"), 0).toInt() == 1; - if (m_useKTextEditor) - { - m_tikzEditorView = m_tikzKTextEditor = new TikzKTextEditorView(this); - } - else + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + m_useKTextEditor = settings.value(QLatin1String("EditorWidget"), 0).toInt() == 1; + if (m_useKTextEditor) { + m_tikzEditorView = m_tikzKTextEditor = new TikzKTextEditorView(this); + } else #endif - { - m_tikzEditorView = m_tikzQtEditorView = new TikzEditorView(this); - m_tikzHighlighter = new TikzHighlighter(m_tikzQtEditorView->editor()->document()); - } -//qCritical() << "TikzEditorView" << t.msecsTo(QTime::currentTime()); - m_commandInserter = new TikzCommandInserter(this); - m_userCommandInserter = new UserCommandInserter(this); - - QWidget *mainWidget = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget); - mainLayout->setSpacing(0); - mainLayout->setMargin(0); - mainLayout->addWidget(m_tikzPreviewController->templateWidget()); - mainLayout->addWidget(m_tikzEditorView); - - m_logDock = new QDockWidget(this); - m_logDock->setObjectName(QLatin1String("LogDock")); - m_logDock->setAllowedAreas(Qt::AllDockWidgetAreas); - m_logDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); - m_logDock->setWindowTitle(tr("&Messages")); - addDockWidget(Qt::BottomDockWidgetArea, m_logDock); - m_logTextEdit = new LogTextEdit; - m_logTextEdit->setWhatsThis(tr("

The messages produced by " - "LaTeX are shown here. If your TikZ code contains errors, " - "then a red border will appear and the errors will be " - "highlighted.

")); - m_logDock->setWidget(m_logTextEdit); - - m_previewDock = new QDockWidget(this); - m_previewDock->setObjectName(QLatin1String("PreviewDock")); - m_previewDock->setAllowedAreas(Qt::AllDockWidgetAreas); - m_previewDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); - m_previewDock->setWindowTitle(tr("Previe&w")); - m_previewDock->setWidget(m_tikzPreviewController->tikzPreview()); - addDockWidget(Qt::RightDockWidgetArea, m_previewDock); - - setCentralWidget(mainWidget); - - createActions(); + { + m_tikzEditorView = m_tikzQtEditorView = new TikzEditorView(this); + m_tikzHighlighter = new TikzHighlighter(m_tikzQtEditorView->editor()->document()); + } + // qCritical() << "TikzEditorView" << t.msecsTo(QTime::currentTime()); + m_commandInserter = new TikzCommandInserter(this); + m_userCommandInserter = new UserCommandInserter(this); + + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget); + mainLayout->setSpacing(0); + mainLayout->setMargin(0); + mainLayout->addWidget(m_tikzPreviewController->templateWidget()); + mainLayout->addWidget(m_tikzEditorView); + + m_logDock = new QDockWidget(this); + m_logDock->setObjectName(QLatin1String("LogDock")); + m_logDock->setAllowedAreas(Qt::AllDockWidgetAreas); + m_logDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable + | QDockWidget::DockWidgetFloatable); + m_logDock->setWindowTitle(tr("&Messages")); + addDockWidget(Qt::BottomDockWidgetArea, m_logDock); + m_logTextEdit = new LogTextEdit; + m_logTextEdit->setWhatsThis(tr("

The messages produced by " + "LaTeX are shown here. If your TikZ code contains errors, " + "then a red border will appear and the errors will be " + "highlighted.

")); + m_logDock->setWidget(m_logTextEdit); + + m_previewDock = new QDockWidget(this); + m_previewDock->setObjectName(QLatin1String("PreviewDock")); + m_previewDock->setAllowedAreas(Qt::AllDockWidgetAreas); + m_previewDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable + | QDockWidget::DockWidgetFloatable); + m_previewDock->setWindowTitle(tr("Previe&w")); + m_previewDock->setWidget(m_tikzPreviewController->tikzPreview()); + addDockWidget(Qt::RightDockWidgetArea, m_previewDock); + + setCentralWidget(mainWidget); + + createActions(); #ifndef KTIKZ_USE_KDE - createToolBars(); // run first in order to be able to add file/editToolBar->toggleViewAction() to the menu - createMenus(); + createToolBars(); // run first in order to be able to add file/editToolBar->toggleViewAction() + // to the menu + createMenus(); #endif -//qCritical() << "createMenus" << t.msecsTo(QTime::currentTime()); - createCommandInsertWidget(); // must happen after createMenus and before readSettings - createStatusBar(); + // qCritical() << "createMenus" << t.msecsTo(QTime::currentTime()); + createCommandInsertWidget(); // must happen after createMenus and before readSettings + createStatusBar(); #ifdef KTIKZ_USE_KDE - setupGUI(ToolBar | Keys | StatusBar | Save ); -#ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) -#endif - { - createGUI("ktikzui.rc"); - } - guiFactory()->addClient(this); -#ifdef KTIKZ_USE_KTEXTEDITOR - if (m_useKTextEditor) - { - createGUI("ktikzui_frameworks.rc"); - guiFactory()->addClient( m_tikzKTextEditor->view() ); - - connect(m_tikzKTextEditor, SIGNAL(documentUrlChanged(const QUrl&)), - this, SLOT(changedUrl(const QUrl&))); - } -#endif + setupGUI(ToolBar | Keys | StatusBar | Save); +# ifdef KTIKZ_USE_KTEXTEDITOR + if (!m_useKTextEditor) +# endif + { + createGUI("ktikzui.rc"); + } + guiFactory()->addClient(this); +# ifdef KTIKZ_USE_KTEXTEDITOR + if (m_useKTextEditor) { + createGUI("ktikzui_frameworks.rc"); + guiFactory()->addClient(m_tikzKTextEditor->view()); + + connect(m_tikzKTextEditor, SIGNAL(documentUrlChanged(const QUrl &)), this, + SLOT(changedUrl(const QUrl &))); + } +# endif #endif - // TODO: check this + // TODO: check this #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - { - setTabOrder(m_tikzPreviewController->templateWidget()->lastTabOrderWidget(), m_tikzQtEditorView->editor()); - connect(m_tikzQtEditorView, SIGNAL(showStatusMessage(QString,int)), - statusBar(), SLOT(showMessage(QString,int))); - } - - - connect(m_commandInserter, SIGNAL(showStatusMessage(QString,int)), - statusBar(), SLOT(showMessage(QString,int))); - - connect(m_tikzEditorView, SIGNAL(modificationChanged(bool)), - this, SLOT(setDocumentModified(bool))); - connect(m_tikzEditorView, SIGNAL(cursorPositionChanged(int,int)), - this, SLOT(showCursorPosition(int,int))); - - connect(m_tikzEditorView, SIGNAL(focusIn()), - this, SLOT(checkForFileChanges())); - connect(m_tikzEditorView, SIGNAL(focusOut()), - this, SLOT(saveLastInternalModifiedDateTime())); - - connect(m_tikzPreviewController, SIGNAL(updateLog(QString,bool)), - m_logTextEdit, SLOT(updateLog(QString,bool))); - connect(m_tikzPreviewController, SIGNAL(appendLog(QString,bool)), - m_logTextEdit, SLOT(appendLog(QString,bool))); - connect(m_tikzPreviewController, SIGNAL(showMouseCoordinates(qreal,qreal,int,int)), - this, SLOT(showMouseCoordinates(qreal,qreal,int,int))); - - connect(m_userCommandInserter, SIGNAL(updateCompleter()), - this, SLOT(updateCompleter())); - - readSettings(); // must be run after defining tikzController and tikzHighlighter, and after creating the toolbars, and after the connects -//qCritical() << "readSettings()" << t.msecsTo(QTime::currentTime()); - - setCurrentUrl(Url()); - setDocumentModified(false); - saveLastInternalModifiedDateTime(); - m_tikzEditorView->setFocus(); - - // delayed initialization -// QTimer::singleShot(0, this, SLOT(init())); // this causes flicker at startup and init() is not executed in a separate thread anyway :( - init(); -//qCritical() << "mainwindow" << t.msecsTo(QTime::currentTime()); + { + setTabOrder(m_tikzPreviewController->templateWidget()->lastTabOrderWidget(), + m_tikzQtEditorView->editor()); + connect(m_tikzQtEditorView, SIGNAL(showStatusMessage(QString, int)), statusBar(), + SLOT(showMessage(QString, int))); + } + + connect(m_commandInserter, SIGNAL(showStatusMessage(QString, int)), statusBar(), + SLOT(showMessage(QString, int))); + + connect(m_tikzEditorView, SIGNAL(modificationChanged(bool)), this, + SLOT(setDocumentModified(bool))); + connect(m_tikzEditorView, SIGNAL(cursorPositionChanged(int, int)), this, + SLOT(showCursorPosition(int, int))); + + connect(m_tikzEditorView, SIGNAL(focusIn()), this, SLOT(checkForFileChanges())); + connect(m_tikzEditorView, SIGNAL(focusOut()), this, SLOT(saveLastInternalModifiedDateTime())); + + connect(m_tikzPreviewController, SIGNAL(updateLog(QString, bool)), m_logTextEdit, + SLOT(updateLog(QString, bool))); + connect(m_tikzPreviewController, SIGNAL(appendLog(QString, bool)), m_logTextEdit, + SLOT(appendLog(QString, bool))); + connect(m_tikzPreviewController, SIGNAL(showMouseCoordinates(qreal, qreal, int, int)), this, + SLOT(showMouseCoordinates(qreal, qreal, int, int))); + + connect(m_userCommandInserter, SIGNAL(updateCompleter()), this, SLOT(updateCompleter())); + + readSettings(); // must be run after defining tikzController and tikzHighlighter, and after + // creating the toolbars, and after the connects + // qCritical() << "readSettings()" << t.msecsTo(QTime::currentTime()); + + setCurrentUrl(Url()); + setDocumentModified(false); + saveLastInternalModifiedDateTime(); + m_tikzEditorView->setFocus(); + + // delayed initialization + // QTimer::singleShot(0, this, SLOT(init())); // this causes flicker at startup and init() is + //not executed in a separate thread anyway :( + init(); + // qCritical() << "mainwindow" << t.msecsTo(QTime::currentTime()); } MainWindow::~MainWindow() { - s_mainWindowList.removeAll(this); + s_mainWindowList.removeAll(this); - writeSettings(); + writeSettings(); #ifndef KTIKZ_USE_KDE - if (m_aboutDialog) - delete m_aboutDialog; - if (m_assistantController) - delete m_assistantController; + if (m_aboutDialog) + delete m_aboutDialog; + if (m_assistantController) + delete m_assistantController; #endif - delete m_tikzPreviewController; + delete m_tikzPreviewController; #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - m_tikzHighlighter->deleteLater(); + m_tikzHighlighter->deleteLater(); } void MainWindow::init() { -//QTime t = QTime::currentTime(); +// QTime t = QTime::currentTime(); #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - m_tikzQtEditorView->setPasteEnabled(); + m_tikzQtEditorView->setPasteEnabled(); - TikzCommandInserter::loadCommands(); -//qCritical() << "TikzCommandInserter::loadCommands()" << t.msecsTo(QTime::currentTime()); + TikzCommandInserter::loadCommands(); +// qCritical() << "TikzCommandInserter::loadCommands()" << t.msecsTo(QTime::currentTime()); #ifdef KTIKZ_USE_KTEXTEDITOR - if (m_useKTextEditor) - m_commandInserter->setEditor(m_tikzKTextEditor->editor()); - else + if (m_useKTextEditor) + m_commandInserter->setEditor(m_tikzKTextEditor->editor()); + else #endif - { - m_commandInserter->setEditor(m_tikzQtEditorView->editor()); - m_tikzHighlighter->setHighlightingRules(m_commandInserter->getHighlightingRules()); - } - - if (m_insertAction) - m_insertAction->setMenu(m_commandInserter->getMenu()); - else - m_commandInserter->showItemsInDockWidget(); - connect(m_userCommandInserter, SIGNAL(insertTag(QString)), m_commandInserter, SLOT(insertTag(QString))); - - // the following disconnect ensures that the following signal is not unnecessarily triggered twice when a file is loaded in a new window - disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); - - applySettings(); // must do this in order to load the command completions -//qCritical() << "applySettings()" << t.msecsTo(QTime::currentTime()); - - if (m_buildAutomatically) - connect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); - - if (m_tikzPreviewController->tempDir().isEmpty()) // then the temporary directory could not be created - m_logTextEdit->updateLog(tr("Error: unable to create a temporary directory in \"%1\". This program will not work!").arg(m_tikzPreviewController->tempDirLocation()), true); -//qCritical() << "init()" << t.msecsTo(QTime::currentTime()); + { + m_commandInserter->setEditor(m_tikzQtEditorView->editor()); + m_tikzHighlighter->setHighlightingRules(m_commandInserter->getHighlightingRules()); + } + + if (m_insertAction) + m_insertAction->setMenu(m_commandInserter->getMenu()); + else + m_commandInserter->showItemsInDockWidget(); + connect(m_userCommandInserter, SIGNAL(insertTag(QString)), m_commandInserter, + SLOT(insertTag(QString))); + + // the following disconnect ensures that the following signal is not unnecessarily triggered + // twice when a file is loaded in a new window + disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); + + applySettings(); // must do this in order to load the command completions + // qCritical() << "applySettings()" << t.msecsTo(QTime::currentTime()); + + if (m_buildAutomatically) + connect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); + + if (m_tikzPreviewController->tempDir() + .isEmpty()) // then the temporary directory could not be created + m_logTextEdit->updateLog(tr("Error: unable to create a temporary directory in \"%1\". This " + "program will not work!") + .arg(m_tikzPreviewController->tempDirLocation()), + true); + // qCritical() << "init()" << t.msecsTo(QTime::currentTime()); } QWidget *MainWindow::widget() { - return this; + return this; } #ifdef KTIKZ_USE_KDE bool MainWindow::queryClose() { - return maybeSave(); + return maybeSave(); } void MainWindow::readProperties(const KConfigGroup &group) { - const Url url(group.readPathEntry(QLatin1String("CurrentUrl"), QString())); - if (url.isValid() && !url.isEmpty()) - loadUrl(url); + const Url url(group.readPathEntry(QLatin1String("CurrentUrl"), QString())); + if (url.isValid() && !url.isEmpty()) + loadUrl(url); } void MainWindow::saveProperties(KConfigGroup &group) { - group.writePathEntry(QLatin1String("CurrentUrl"), m_currentUrl.url()); + group.writePathEntry(QLatin1String("CurrentUrl"), m_currentUrl.url()); } #endif void MainWindow::closeEvent(QCloseEvent *event) { - if (maybeSave()) - { - QApplication::restoreOverrideCursor(); - event->accept(); - } - else - event->ignore(); + if (maybeSave()) { + QApplication::restoreOverrideCursor(); + event->accept(); + } else + event->ignore(); } void MainWindow::newFile() { - MainWindow *newMainWindow = new MainWindow; - newMainWindow->show(); + MainWindow *newMainWindow = new MainWindow; + newMainWindow->show(); } bool MainWindow::closeFile() { - if (maybeSave()) - { - disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); - m_tikzEditorView->clear(); - connect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); - setCurrentUrl(Url()); - m_tikzPreviewController->emptyPreview(); // abort still running processes - m_logTextEdit->updateLog(QString(), false); // clear log window - m_mouseCoordinatesLabel->setText(QString()); - return true; - } - return false; + if (maybeSave()) { + disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); + m_tikzEditorView->clear(); + connect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); + setCurrentUrl(Url()); + m_tikzPreviewController->emptyPreview(); // abort still running processes + m_logTextEdit->updateLog(QString(), false); // clear log window + m_mouseCoordinatesLabel->setText(QString()); + return true; + } + return false; } void MainWindow::open() { - const Url openUrl = FileDialog::getOpenUrl(this, tr("Open PGF source file"), m_lastUrl, QLatin1String("text/x-pgf")); - if (openUrl.isValid() && !openUrl.isEmpty()) - loadUrl(openUrl); + const Url openUrl = FileDialog::getOpenUrl(this, tr("Open PGF source file"), m_lastUrl, + QLatin1String("text/x-pgf")); + if (openUrl.isValid() && !openUrl.isEmpty()) + loadUrl(openUrl); } bool MainWindow::save() { - if (!m_currentUrl.isValid() || m_currentUrl.isEmpty()) - return saveAs(); - else - { - if (m_isModifiedExternally) - { - checkForFileChanges(Saving); - return true; - } - else - return saveUrl(m_currentUrl); - } + if (!m_currentUrl.isValid() || m_currentUrl.isEmpty()) + return saveAs(); + else { + if (m_isModifiedExternally) { + checkForFileChanges(Saving); + return true; + } else + return saveUrl(m_currentUrl); + } } bool MainWindow::saveAs() { - const Url saveAsUrl = FileDialog::getSaveUrl(this, tr("Save PGF source file"), Url(m_currentUrl), QLatin1String("text/x-pgf")); - if (!saveAsUrl.isValid() || saveAsUrl.isEmpty()) - return false; - return saveUrl(saveAsUrl); + const Url saveAsUrl = FileDialog::getSaveUrl(this, tr("Save PGF source file"), + Url(m_currentUrl), QLatin1String("text/x-pgf")); + if (!saveAsUrl.isValid() || saveAsUrl.isEmpty()) + return false; + return saveUrl(saveAsUrl); } void MainWindow::reload() { - const QUrl currentUrl = m_currentUrl; - if (closeFile()) - { - saveLastInternalModifiedDateTime(); - loadUrl(currentUrl); - } + const QUrl currentUrl = m_currentUrl; + if (closeFile()) { + saveLastInternalModifiedDateTime(); + loadUrl(currentUrl); + } } void MainWindow::checkForFileChanges(const FileCheckMoment &moment) { - if (moment == FocusIn) - { - QDateTime lastExternalModifiedDateTime(QFileInfo(m_currentUrl.path()).lastModified()); - if (lastExternalModifiedDateTime > m_lastInternalModifiedDateTime) - m_isModifiedExternally = true; - else // when the fileChangedWarningMessageBox below is cancelled, the main window is focused in again with m_isModifiedExternally == true so this slot is called again, but now m_lastInternalModifiedDateTime has been updated (during focusOut) and now we don't want to show the dialog again - return; - } - - if (!m_isModifiedExternally) - return; - - m_isModifiedExternally = false; - QPointer fileChangedWarningMessageBox = new QMessageBox(this); - fileChangedWarningMessageBox->setText(tr("The document was modified by another program.\nWhat do you want to do?")); - fileChangedWarningMessageBox->setWindowTitle(KtikzApplication::applicationName()); - fileChangedWarningMessageBox->setIcon(QMessageBox::Warning); - QAbstractButton *overwriteButton = fileChangedWarningMessageBox->addButton(tr("&Overwrite"), QMessageBox::AcceptRole); - QAbstractButton *reloadButton; - switch (moment) - { - case Saving: - reloadButton = fileChangedWarningMessageBox->addButton(tr("&Save under another name"), QMessageBox::AcceptRole); - break; - case Closing: - reloadButton = fileChangedWarningMessageBox->addButton(tr("&Close without saving"), QMessageBox::AcceptRole); - break; - case FocusIn: - default: - reloadButton = fileChangedWarningMessageBox->addButton(tr("&Reload file"), QMessageBox::AcceptRole); - break; - } - fileChangedWarningMessageBox->addButton(QMessageBox::Cancel); - fileChangedWarningMessageBox->exec(); - if (fileChangedWarningMessageBox->clickedButton() == overwriteButton) - saveUrl(m_currentUrl); - else if (fileChangedWarningMessageBox->clickedButton() == reloadButton) - switch (moment) - { - case Saving: - saveAs(); - break; - case Closing: - // do nothing since the file will be closed anyway - break; - case FocusIn: - default: - reload(); - break; - } - else // cancel (check again on "Save" or "Close") - m_isModifiedExternally = true; - delete fileChangedWarningMessageBox; + if (moment == FocusIn) { + QDateTime lastExternalModifiedDateTime(QFileInfo(m_currentUrl.path()).lastModified()); + if (lastExternalModifiedDateTime > m_lastInternalModifiedDateTime) + m_isModifiedExternally = true; + else // when the fileChangedWarningMessageBox below is cancelled, the main window is focused + // in again with m_isModifiedExternally == true so this slot is called again, but now + // m_lastInternalModifiedDateTime has been updated (during focusOut) and now we don't + // want to show the dialog again + return; + } + + if (!m_isModifiedExternally) + return; + + m_isModifiedExternally = false; + QPointer fileChangedWarningMessageBox = new QMessageBox(this); + fileChangedWarningMessageBox->setText( + tr("The document was modified by another program.\nWhat do you want to do?")); + fileChangedWarningMessageBox->setWindowTitle(KtikzApplication::applicationName()); + fileChangedWarningMessageBox->setIcon(QMessageBox::Warning); + QAbstractButton *overwriteButton = + fileChangedWarningMessageBox->addButton(tr("&Overwrite"), QMessageBox::AcceptRole); + QAbstractButton *reloadButton; + switch (moment) { + case Saving: + reloadButton = fileChangedWarningMessageBox->addButton(tr("&Save under another name"), + QMessageBox::AcceptRole); + break; + case Closing: + reloadButton = fileChangedWarningMessageBox->addButton(tr("&Close without saving"), + QMessageBox::AcceptRole); + break; + case FocusIn: + default: + reloadButton = fileChangedWarningMessageBox->addButton(tr("&Reload file"), + QMessageBox::AcceptRole); + break; + } + fileChangedWarningMessageBox->addButton(QMessageBox::Cancel); + fileChangedWarningMessageBox->exec(); + if (fileChangedWarningMessageBox->clickedButton() == overwriteButton) + saveUrl(m_currentUrl); + else if (fileChangedWarningMessageBox->clickedButton() == reloadButton) + switch (moment) { + case Saving: + saveAs(); + break; + case Closing: + // do nothing since the file will be closed anyway + break; + case FocusIn: + default: + reload(); + break; + } + else // cancel (check again on "Save" or "Close") + m_isModifiedExternally = true; + delete fileChangedWarningMessageBox; } void MainWindow::saveLastInternalModifiedDateTime() { - m_lastInternalModifiedDateTime = QDateTime::currentDateTime(); + m_lastInternalModifiedDateTime = QDateTime::currentDateTime(); } /***************************************************************************/ void MainWindow::showTikzDocumentation() { - QApplication::setOverrideCursor(Qt::WaitCursor); - - const QString tikzDocFile = TikzDocumentationController::tikzDocumentationPath(); - const bool tikzDocFileExists = QFileInfo(tikzDocFile).exists(); // true if tikzDocFile is local and exists - const QUrl tikzDocUrl = tikzDocFileExists ? QUrl(QLatin1String("file:///") + tikzDocFile) : QUrl(tikzDocFile); - - if (!QDesktopServices::openUrl(tikzDocUrl)) - { - if (!tikzDocFileExists) - QMessageBox::warning(this, KtikzApplication::applicationName(), - tr("Cannot find TikZ documentation.\n" - "Go to Settings -> Configure %1 and change in the \"General\" tab " - "the path to the TikZ documentation.") - .arg(KtikzApplication::applicationName())); - else // if tikzDocFile is local and exists then failure to open it is caused by not finding the correct application - QMessageBox::warning(this, KtikzApplication::applicationName(), - tr("Cannot open TikZ documentation.\n" - "No application is found which can open the file \"%1\".") - .arg(tikzDocFile)); - } - - QApplication::restoreOverrideCursor(); + QApplication::setOverrideCursor(Qt::WaitCursor); + + const QString tikzDocFile = TikzDocumentationController::tikzDocumentationPath(); + const bool tikzDocFileExists = + QFileInfo(tikzDocFile).exists(); // true if tikzDocFile is local and exists + const QUrl tikzDocUrl = + tikzDocFileExists ? QUrl(QLatin1String("file:///") + tikzDocFile) : QUrl(tikzDocFile); + + if (!QDesktopServices::openUrl(tikzDocUrl)) { + if (!tikzDocFileExists) + QMessageBox::warning( + this, KtikzApplication::applicationName(), + tr("Cannot find TikZ documentation.\n" + "Go to Settings -> Configure %1 and change in the \"General\" tab " + "the path to the TikZ documentation.") + .arg(KtikzApplication::applicationName())); + else // if tikzDocFile is local and exists then failure to open it is caused by not finding + // the correct application + QMessageBox::warning(this, KtikzApplication::applicationName(), + tr("Cannot open TikZ documentation.\n" + "No application is found which can open the file \"%1\".") + .arg(tikzDocFile)); + } + + QApplication::restoreOverrideCursor(); } #ifndef KTIKZ_USE_KDE void MainWindow::about() { - if (!m_aboutDialog) - m_aboutDialog = new AboutDialog(this); - m_aboutDialog->exec(); + if (!m_aboutDialog) + m_aboutDialog = new AboutDialog(this); + m_aboutDialog->exec(); } void MainWindow::showDocumentation() { - if (!m_assistantController) - m_assistantController = new AssistantController; - m_assistantController->showDocumentation(); + if (!m_assistantController) + m_assistantController = new AssistantController; + m_assistantController->showDocumentation(); } #endif @@ -518,25 +526,25 @@ void MainWindow::showDocumentation() bool MainWindow::isDocumentModified() const { - return isWindowModified(); + return isWindowModified(); } void MainWindow::setDocumentModified(bool isModified) { - setWindowModified(isModified); + setWindowModified(isModified); #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - { - m_saveAction->setEnabled(isModified); - m_saveAsAction->setEnabled(m_currentUrl.isValid() && !m_currentUrl.isEmpty()); - } + { + m_saveAction->setEnabled(isModified); + m_saveAsAction->setEnabled(m_currentUrl.isValid() && !m_currentUrl.isEmpty()); + } } void MainWindow::updateLog() { - m_logTextEdit->updateLog(m_tikzPreviewController->getLogText()); -// m_logTextEdit->updateLog(m_tikzController->getLogText(), m_tikzController->hasRunFailed()); + m_logTextEdit->updateLog(m_tikzPreviewController->getLogText()); + // m_logTextEdit->updateLog(m_tikzController->getLogText(), m_tikzController->hasRunFailed()); } /***************************************************************************/ @@ -544,615 +552,629 @@ void MainWindow::updateLog() #ifdef KTIKZ_USE_KDE void MainWindow::toggleWhatsThisMode() { - if (QWhatsThis::inWhatsThisMode()) - QWhatsThis::leaveWhatsThisMode(); - else - QWhatsThis::enterWhatsThisMode(); + if (QWhatsThis::inWhatsThisMode()) + QWhatsThis::leaveWhatsThisMode(); + else + QWhatsThis::enterWhatsThisMode(); } #endif void MainWindow::createActions() { - // Editor related actions + // Editor related actions #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - { - m_saveAction = StandardAction::save(this, SLOT(save()), this); - m_saveAction->setStatusTip(tr("Save the current document to disk")); - m_saveAction->setWhatsThis(tr("

Save the current document to disk.

")); - - m_saveAsAction = StandardAction::saveAs(this, SLOT(saveAs()), this); - m_saveAsAction->setStatusTip(tr("Save the document under a new name")); - m_saveAsAction->setWhatsThis(tr("

Save the document under a new name.

")); - - m_reloadAction = new Action(Icon(QStringLiteral("view-refresh")), tr("Reloa&d"), this, QLatin1String("file_reload")); - m_reloadAction->setShortcut(QKeySequence::Refresh); - m_reloadAction->setStatusTip(tr("Reload the current document")); - m_reloadAction->setWhatsThis(tr("

Reload the current document from disk.

")); - connect(m_reloadAction, SIGNAL(triggered()), this, SLOT(reload())); - } - - - // General action - m_newAction = StandardAction::openNew(this, SLOT(newFile()), this); - m_newAction->setStatusTip(tr("Create a new document")); - m_newAction->setWhatsThis(tr("

Create a new document.

")); - - m_openAction = StandardAction::open(this, SLOT(open()), this); - m_openAction->setStatusTip(tr("Open an existing file")); - m_openAction->setWhatsThis(tr("

Open an existing file.

")); - - m_openRecentAction = StandardAction::openRecent(this, SLOT(loadUrl(QUrl)), this); - m_openRecentAction->setStatusTip(tr("Open a recently opened file")); - m_openRecentAction->setWhatsThis(tr("

Open a recently opened file.

")); - - m_closeAction = StandardAction::close(this, SLOT(closeFile()), this); - m_closeAction->setStatusTip(tr("Close the current document")); - m_closeAction->setWhatsThis(tr("

Close the current document.

")); - - m_exitAction = StandardAction::quit(this, SLOT(close()), this); - m_exitAction->setStatusTip(tr("Exit the application")); - m_exitAction->setWhatsThis(tr("

Exit the application.

")); - - // View - m_buildAction = new Action(Icon(QLatin1String("run-build")), tr("&Build"), this, QLatin1String("build")); - //m_buildAction->setShortcut(tr("Ctrl+B", "View|Build")); - m_buildAction->setStatusTip(tr("Build preview")); - m_buildAction->setWhatsThis(tr("

Generate preview by building the current TikZ code in the editor.

")); - connect(m_buildAction, SIGNAL(triggered()), m_tikzPreviewController, SLOT(regeneratePreview())); - - m_viewLogAction = new Action(Icon(QLatin1String("run-build-file")), tr("View &Log"), this, QLatin1String("view_log")); - m_viewLogAction->setStatusTip(tr("View log messages produced by the last executed process")); - m_viewLogAction->setWhatsThis(tr("

Show the log messages produced by the last executed process in the Messages box.

")); - connect(m_viewLogAction, SIGNAL(triggered()), this, SLOT(updateLog())); - - // Configure - m_configureAction = StandardAction::preferences(this, SLOT(configure()), this); - m_configureAction->setText(tr("&Configure %1...").arg(KtikzApplication::applicationName())); - m_configureAction->setStatusTip(tr("Configure the settings of this application")); - m_configureAction->setWhatsThis(tr("

Configure the settings of this application.

")); + { + m_saveAction = StandardAction::save(this, SLOT(save()), this); + m_saveAction->setStatusTip(tr("Save the current document to disk")); + m_saveAction->setWhatsThis(tr("

Save the current document to disk.

")); + + m_saveAsAction = StandardAction::saveAs(this, SLOT(saveAs()), this); + m_saveAsAction->setStatusTip(tr("Save the document under a new name")); + m_saveAsAction->setWhatsThis(tr("

Save the document under a new name.

")); + + m_reloadAction = new Action(Icon(QStringLiteral("view-refresh")), tr("Reloa&d"), this, + QLatin1String("file_reload")); + m_reloadAction->setShortcut(QKeySequence::Refresh); + m_reloadAction->setStatusTip(tr("Reload the current document")); + m_reloadAction->setWhatsThis(tr("

Reload the current document from disk.

")); + connect(m_reloadAction, SIGNAL(triggered()), this, SLOT(reload())); + } + + // General action + m_newAction = StandardAction::openNew(this, SLOT(newFile()), this); + m_newAction->setStatusTip(tr("Create a new document")); + m_newAction->setWhatsThis(tr("

Create a new document.

")); + + m_openAction = StandardAction::open(this, SLOT(open()), this); + m_openAction->setStatusTip(tr("Open an existing file")); + m_openAction->setWhatsThis(tr("

Open an existing file.

")); + + m_openRecentAction = StandardAction::openRecent(this, SLOT(loadUrl(QUrl)), this); + m_openRecentAction->setStatusTip(tr("Open a recently opened file")); + m_openRecentAction->setWhatsThis(tr("

Open a recently opened file.

")); + + m_closeAction = StandardAction::close(this, SLOT(closeFile()), this); + m_closeAction->setStatusTip(tr("Close the current document")); + m_closeAction->setWhatsThis(tr("

Close the current document.

")); + + m_exitAction = StandardAction::quit(this, SLOT(close()), this); + m_exitAction->setStatusTip(tr("Exit the application")); + m_exitAction->setWhatsThis(tr("

Exit the application.

")); + + // View + m_buildAction = new Action(Icon(QLatin1String("run-build")), tr("&Build"), this, + QLatin1String("build")); + // m_buildAction->setShortcut(tr("Ctrl+B", "View|Build")); + m_buildAction->setStatusTip(tr("Build preview")); + m_buildAction->setWhatsThis( + tr("

Generate preview by building the current TikZ code in the editor.

")); + connect(m_buildAction, SIGNAL(triggered()), m_tikzPreviewController, SLOT(regeneratePreview())); + + m_viewLogAction = new Action(Icon(QLatin1String("run-build-file")), tr("View &Log"), this, + QLatin1String("view_log")); + m_viewLogAction->setStatusTip(tr("View log messages produced by the last executed process")); + m_viewLogAction->setWhatsThis(tr("

Show the log messages produced by the last executed " + "process in the Messages box.

")); + connect(m_viewLogAction, SIGNAL(triggered()), this, SLOT(updateLog())); + + // Configure + m_configureAction = StandardAction::preferences(this, SLOT(configure()), this); + m_configureAction->setText(tr("&Configure %1...").arg(KtikzApplication::applicationName())); + m_configureAction->setStatusTip(tr("Configure the settings of this application")); + m_configureAction->setWhatsThis(tr("

Configure the settings of this application.

")); #ifdef KTIKZ_USE_KDE - addActionCloneToCollection(QLatin1String("toggle_preview"), m_previewDock->toggleViewAction()); - addActionCloneToCollection(QLatin1String("toggle_log"), m_logDock->toggleViewAction()); + addActionCloneToCollection(QLatin1String("toggle_preview"), m_previewDock->toggleViewAction()); + addActionCloneToCollection(QLatin1String("toggle_log"), m_logDock->toggleViewAction()); #endif - // Help - m_showTikzDocAction = new Action(Icon(QLatin1String("help-contents")), tr("TikZ &Manual"), this, QLatin1String("show_tikz_doc")); - m_showTikzDocAction->setStatusTip(tr("Show the manual of TikZ and PGF")); - m_showTikzDocAction->setWhatsThis(tr("

Show the manual of TikZ and PGF.

")); - connect(m_showTikzDocAction, SIGNAL(triggered()), this, SLOT(showTikzDocumentation())); + // Help + m_showTikzDocAction = new Action(Icon(QLatin1String("help-contents")), tr("TikZ &Manual"), this, + QLatin1String("show_tikz_doc")); + m_showTikzDocAction->setStatusTip(tr("Show the manual of TikZ and PGF")); + m_showTikzDocAction->setWhatsThis(tr("

Show the manual of TikZ and PGF.

")); + connect(m_showTikzDocAction, SIGNAL(triggered()), this, SLOT(showTikzDocumentation())); #ifdef KTIKZ_USE_KDE - m_whatsThisAction = KStandardAction::whatsThis(this, SLOT(toggleWhatsThisMode()), this); + m_whatsThisAction = KStandardAction::whatsThis(this, SLOT(toggleWhatsThisMode()), this); #else - m_helpAction = new QAction(Icon(QLatin1String("help-contents")), tr("%1 &Handbook").arg(KtikzApplication::applicationName()), this); - m_helpAction->setStatusTip(tr("Show the application's documentation")); - m_helpAction->setShortcut(QKeySequence::HelpContents); - connect(m_helpAction, SIGNAL(triggered()), this, SLOT(showDocumentation())); - - m_whatsThisAction = QWhatsThis::createAction(this); - m_whatsThisAction->setIcon(Icon(QLatin1String("help-contextual"))); - m_whatsThisAction->setStatusTip(tr("Show simple description of any widget")); - - m_aboutAction = new QAction(QIcon(QLatin1String(":/icons/qtikz-22.png")), tr("&About %1").arg(KtikzApplication::applicationName()), this); - m_aboutAction->setStatusTip(tr("Show the application's About box")); - connect(m_aboutAction, SIGNAL(triggered()), this, SLOT(about())); - - m_aboutQtAction = new QAction(QIcon(QLatin1String(":/icons/qt-logo-22.png")), tr("About &Qt"), this); - m_aboutQtAction->setStatusTip(tr("Show the Qt library's About box")); - connect(m_aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + m_helpAction = new QAction(Icon(QLatin1String("help-contents")), + tr("%1 &Handbook").arg(KtikzApplication::applicationName()), this); + m_helpAction->setStatusTip(tr("Show the application's documentation")); + m_helpAction->setShortcut(QKeySequence::HelpContents); + connect(m_helpAction, SIGNAL(triggered()), this, SLOT(showDocumentation())); + + m_whatsThisAction = QWhatsThis::createAction(this); + m_whatsThisAction->setIcon(Icon(QLatin1String("help-contextual"))); + m_whatsThisAction->setStatusTip(tr("Show simple description of any widget")); + + m_aboutAction = new QAction(QIcon(QLatin1String(":/icons/qtikz-22.png")), + tr("&About %1").arg(KtikzApplication::applicationName()), this); + m_aboutAction->setStatusTip(tr("Show the application's About box")); + connect(m_aboutAction, SIGNAL(triggered()), this, SLOT(about())); + + m_aboutQtAction = + new QAction(QIcon(QLatin1String(":/icons/qt-logo-22.png")), tr("About &Qt"), this); + m_aboutQtAction->setStatusTip(tr("Show the Qt library's About box")); + connect(m_aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); #endif } #ifdef KTIKZ_USE_KDE void MainWindow::addActionCloneToCollection(const QString &actionName, QAction *action) { - // XXX This is a dirty hack to avoid the warning "Attempt to use QAction with KXMLGUIFactory" - KToggleAction *actionClone = new KToggleAction(this); - actionCollection()->addAction(actionName, actionClone); - actionClone->setText(action->text()); - actionClone->setIcon(action->icon()); - connect(action, SIGNAL(toggled(bool)), actionClone, SLOT(setChecked(bool))); - connect(actionClone, SIGNAL(triggered()), action, SLOT(trigger())); + // XXX This is a dirty hack to avoid the warning "Attempt to use QAction with KXMLGUIFactory" + KToggleAction *actionClone = new KToggleAction(this); + actionCollection()->addAction(actionName, actionClone); + actionClone->setText(action->text()); + actionClone->setIcon(action->icon()); + connect(action, SIGNAL(toggled(bool)), actionClone, SLOT(setChecked(bool))); + connect(actionClone, SIGNAL(triggered()), action, SLOT(trigger())); } #else void MainWindow::createMenus() { - QMenu *fileMenu = menuBar()->addMenu(tr("&File")); - fileMenu->addAction(m_newAction); - fileMenu->addAction(m_openAction); - fileMenu->addAction(m_openRecentAction); - fileMenu->addSeparator(); - fileMenu->addAction(m_saveAction); - fileMenu->addAction(m_saveAsAction); - fileMenu->addAction(m_tikzPreviewController->exportAction()); - fileMenu->addSeparator(); - fileMenu->addAction(m_reloadAction); - fileMenu->addSeparator(); - fileMenu->addAction(m_tikzPreviewController->printPreviewAction()); - fileMenu->addAction(m_tikzPreviewController->printAction()); - fileMenu->addSeparator(); - fileMenu->addAction(m_closeAction); - fileMenu->addSeparator(); - fileMenu->addAction(m_exitAction); - - menuBar()->addMenu(m_tikzEditorView->editMenu()); - menuBar()->addMenu(m_tikzEditorView->bookmarksMenu()); - - QMenu *viewMenu = m_tikzPreviewController->menu(); - viewMenu->insertAction(viewMenu->actions().at(viewMenu->actions().size() - 2), m_buildAction); - viewMenu->addAction(m_viewLogAction); - menuBar()->addMenu(viewMenu); - - m_settingsMenu = menuBar()->addMenu(tr("&Settings")); - QMenu *toolBarMenu = new QMenu(tr("&Toolbars"), this); - toolBarMenu->setIcon(Icon(QLatin1String("configure-toolbars"))); - toolBarMenu->menuAction()->setStatusTip(tr("Show or hide toolbars")); - toolBarMenu->addAction(m_fileToolBar->toggleViewAction()); - toolBarMenu->addAction(m_editToolBar->toggleViewAction()); - toolBarMenu->addAction(m_viewToolBar->toggleViewAction()); - toolBarMenu->addAction(m_runToolBar->toggleViewAction()); - m_fileToolBar->toggleViewAction()->setStatusTip(tr("Show toolbar \"%1\"").arg(m_fileToolBar->windowTitle())); - m_editToolBar->toggleViewAction()->setStatusTip(tr("Show toolbar \"%1\"").arg(m_editToolBar->windowTitle())); - m_viewToolBar->toggleViewAction()->setStatusTip(tr("Show toolbar \"%1\"").arg(m_viewToolBar->windowTitle())); - m_runToolBar->toggleViewAction()->setStatusTip(tr("Show toolbar \"%1\"").arg(m_runToolBar->windowTitle())); - m_settingsMenu->addMenu(toolBarMenu); - m_sideBarMenu = new QMenu(tr("&Sidebars"), this); - m_sideBarMenu->setIcon(Icon(QLatin1String("configure-toolbars"))); - m_sideBarMenu->menuAction()->setStatusTip(tr("Show or hide sidebars")); - m_sideBarMenu->addAction(m_previewDock->toggleViewAction()); - m_sideBarMenu->addAction(m_logDock->toggleViewAction()); - m_previewDock->toggleViewAction()->setStatusTip(tr("Show sidebar \"%1\"").arg(m_previewDock->windowTitle())); - m_logDock->toggleViewAction()->setStatusTip(tr("Show sidebar \"%1\"").arg(m_logDock->windowTitle())); - m_settingsMenu->addMenu(m_sideBarMenu); - m_settingsMenu->addSeparator(); - m_settingsMenu->addAction(m_configureAction); - connect(m_fileToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setToolBarStatusTip(bool))); - connect(m_editToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setToolBarStatusTip(bool))); - connect(m_viewToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setToolBarStatusTip(bool))); - connect(m_runToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setToolBarStatusTip(bool))); - connect(m_previewDock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setDockWidgetStatusTip(bool))); - connect(m_logDock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setDockWidgetStatusTip(bool))); - - menuBar()->addSeparator(); - - QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); - helpMenu->addAction(m_helpAction); - helpMenu->addAction(m_showTikzDocAction); - helpMenu->addAction(m_whatsThisAction); - helpMenu->addSeparator(); - helpMenu->addAction(m_aboutAction); - helpMenu->addAction(m_aboutQtAction); + QMenu *fileMenu = menuBar()->addMenu(tr("&File")); + fileMenu->addAction(m_newAction); + fileMenu->addAction(m_openAction); + fileMenu->addAction(m_openRecentAction); + fileMenu->addSeparator(); + fileMenu->addAction(m_saveAction); + fileMenu->addAction(m_saveAsAction); + fileMenu->addAction(m_tikzPreviewController->exportAction()); + fileMenu->addSeparator(); + fileMenu->addAction(m_reloadAction); + fileMenu->addSeparator(); + fileMenu->addAction(m_tikzPreviewController->printPreviewAction()); + fileMenu->addAction(m_tikzPreviewController->printAction()); + fileMenu->addSeparator(); + fileMenu->addAction(m_closeAction); + fileMenu->addSeparator(); + fileMenu->addAction(m_exitAction); + + menuBar()->addMenu(m_tikzEditorView->editMenu()); + menuBar()->addMenu(m_tikzEditorView->bookmarksMenu()); + + QMenu *viewMenu = m_tikzPreviewController->menu(); + viewMenu->insertAction(viewMenu->actions().at(viewMenu->actions().size() - 2), m_buildAction); + viewMenu->addAction(m_viewLogAction); + menuBar()->addMenu(viewMenu); + + m_settingsMenu = menuBar()->addMenu(tr("&Settings")); + QMenu *toolBarMenu = new QMenu(tr("&Toolbars"), this); + toolBarMenu->setIcon(Icon(QLatin1String("configure-toolbars"))); + toolBarMenu->menuAction()->setStatusTip(tr("Show or hide toolbars")); + toolBarMenu->addAction(m_fileToolBar->toggleViewAction()); + toolBarMenu->addAction(m_editToolBar->toggleViewAction()); + toolBarMenu->addAction(m_viewToolBar->toggleViewAction()); + toolBarMenu->addAction(m_runToolBar->toggleViewAction()); + m_fileToolBar->toggleViewAction()->setStatusTip( + tr("Show toolbar \"%1\"").arg(m_fileToolBar->windowTitle())); + m_editToolBar->toggleViewAction()->setStatusTip( + tr("Show toolbar \"%1\"").arg(m_editToolBar->windowTitle())); + m_viewToolBar->toggleViewAction()->setStatusTip( + tr("Show toolbar \"%1\"").arg(m_viewToolBar->windowTitle())); + m_runToolBar->toggleViewAction()->setStatusTip( + tr("Show toolbar \"%1\"").arg(m_runToolBar->windowTitle())); + m_settingsMenu->addMenu(toolBarMenu); + m_sideBarMenu = new QMenu(tr("&Sidebars"), this); + m_sideBarMenu->setIcon(Icon(QLatin1String("configure-toolbars"))); + m_sideBarMenu->menuAction()->setStatusTip(tr("Show or hide sidebars")); + m_sideBarMenu->addAction(m_previewDock->toggleViewAction()); + m_sideBarMenu->addAction(m_logDock->toggleViewAction()); + m_previewDock->toggleViewAction()->setStatusTip( + tr("Show sidebar \"%1\"").arg(m_previewDock->windowTitle())); + m_logDock->toggleViewAction()->setStatusTip( + tr("Show sidebar \"%1\"").arg(m_logDock->windowTitle())); + m_settingsMenu->addMenu(m_sideBarMenu); + m_settingsMenu->addSeparator(); + m_settingsMenu->addAction(m_configureAction); + connect(m_fileToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setToolBarStatusTip(bool))); + connect(m_editToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setToolBarStatusTip(bool))); + connect(m_viewToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setToolBarStatusTip(bool))); + connect(m_runToolBar->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setToolBarStatusTip(bool))); + connect(m_previewDock->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setDockWidgetStatusTip(bool))); + connect(m_logDock->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setDockWidgetStatusTip(bool))); + + menuBar()->addSeparator(); + + QMenu *helpMenu = menuBar()->addMenu(tr("&Help")); + helpMenu->addAction(m_helpAction); + helpMenu->addAction(m_showTikzDocAction); + helpMenu->addAction(m_whatsThisAction); + helpMenu->addSeparator(); + helpMenu->addAction(m_aboutAction); + helpMenu->addAction(m_aboutQtAction); } void MainWindow::createToolBars() { - m_fileToolBar = addToolBar(tr("File")); - m_fileToolBar->setObjectName(QLatin1String("FileToolBar")); - m_fileToolBar->addAction(m_newAction); - m_fileToolBar->addAction(m_openAction); - m_fileToolBar->addAction(m_saveAction); - m_fileToolBar->addAction(m_closeAction); - - m_editToolBar = m_tikzEditorView->toolBar(); - addToolBar(m_editToolBar); - - QList viewAndRunToolBars = m_tikzPreviewController->toolBars(); - addToolBar(viewAndRunToolBars.at(0)); - viewAndRunToolBars.at(1)->insertAction(viewAndRunToolBars.at(1)->actions().at(0), m_buildAction); - viewAndRunToolBars.at(1)->addAction(m_viewLogAction); - addToolBar(viewAndRunToolBars.at(1)); - m_viewToolBar = viewAndRunToolBars.at(0); - m_runToolBar = viewAndRunToolBars.at(1); - - setToolBarStyle(); + m_fileToolBar = addToolBar(tr("File")); + m_fileToolBar->setObjectName(QLatin1String("FileToolBar")); + m_fileToolBar->addAction(m_newAction); + m_fileToolBar->addAction(m_openAction); + m_fileToolBar->addAction(m_saveAction); + m_fileToolBar->addAction(m_closeAction); + + m_editToolBar = m_tikzEditorView->toolBar(); + addToolBar(m_editToolBar); + + QList viewAndRunToolBars = m_tikzPreviewController->toolBars(); + addToolBar(viewAndRunToolBars.at(0)); + viewAndRunToolBars.at(1)->insertAction(viewAndRunToolBars.at(1)->actions().at(0), + m_buildAction); + viewAndRunToolBars.at(1)->addAction(m_viewLogAction); + addToolBar(viewAndRunToolBars.at(1)); + m_viewToolBar = viewAndRunToolBars.at(0); + m_runToolBar = viewAndRunToolBars.at(1); + + setToolBarStyle(); } void MainWindow::setToolBarStyle() { - QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - - int toolBarStyleNumber = settings.value(QLatin1String("ToolBarStyle"), 0).toInt(); - Qt::ToolButtonStyle toolBarStyle = Qt::ToolButtonIconOnly; - switch (toolBarStyleNumber) - { - case 0: - toolBarStyle = Qt::ToolButtonIconOnly; - break; - case 1: - toolBarStyle = Qt::ToolButtonTextOnly; - break; - case 2: - toolBarStyle = Qt::ToolButtonTextBesideIcon; - break; - case 3: - toolBarStyle = Qt::ToolButtonTextUnderIcon; - break; - } - - m_fileToolBar->setToolButtonStyle(toolBarStyle); - m_editToolBar->setToolButtonStyle(toolBarStyle); - m_tikzPreviewController->setToolBarStyle(toolBarStyle); - - settings.endGroup(); + QSettings settings; + settings.beginGroup(QLatin1String("MainWindow")); + + int toolBarStyleNumber = settings.value(QLatin1String("ToolBarStyle"), 0).toInt(); + Qt::ToolButtonStyle toolBarStyle = Qt::ToolButtonIconOnly; + switch (toolBarStyleNumber) { + case 0: + toolBarStyle = Qt::ToolButtonIconOnly; + break; + case 1: + toolBarStyle = Qt::ToolButtonTextOnly; + break; + case 2: + toolBarStyle = Qt::ToolButtonTextBesideIcon; + break; + case 3: + toolBarStyle = Qt::ToolButtonTextUnderIcon; + break; + } + + m_fileToolBar->setToolButtonStyle(toolBarStyle); + m_editToolBar->setToolButtonStyle(toolBarStyle); + m_tikzPreviewController->setToolBarStyle(toolBarStyle); + + settings.endGroup(); } #endif void MainWindow::createCommandInsertWidget() { - // insert global commands widget - QSettings settings; - bool commandsInDock = settings.value(QLatin1String("CommandsInDock"), false).toBool(); + // insert global commands widget + QSettings settings; + bool commandsInDock = settings.value(QLatin1String("CommandsInDock"), false).toBool(); - if (commandsInDock) - { - m_commandsDock = m_commandInserter->getDockWidget(this); - addDockWidget(Qt::LeftDockWidgetArea, m_commandsDock); + if (commandsInDock) { + m_commandsDock = m_commandInserter->getDockWidget(this); + addDockWidget(Qt::LeftDockWidgetArea, m_commandsDock); #ifdef KTIKZ_USE_KDE - actionCollection()->addAction(QLatin1String("toggle_commands_list"), m_commandsDock->toggleViewAction()); + actionCollection()->addAction(QLatin1String("toggle_commands_list"), + m_commandsDock->toggleViewAction()); #else - m_sideBarMenu->insertAction(m_sideBarMenu->actions().at(1), m_commandsDock->toggleViewAction()); + m_sideBarMenu->insertAction(m_sideBarMenu->actions().at(1), + m_commandsDock->toggleViewAction()); #endif - connect(m_commandsDock->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(setDockWidgetStatusTip(bool))); - } - else - { - // add commands action (menu will be added later in init()) - m_insertAction = new Action(tr("&Insert"), this, QLatin1String("insert")); + connect(m_commandsDock->toggleViewAction(), SIGNAL(toggled(bool)), this, + SLOT(setDockWidgetStatusTip(bool))); + } else { + // add commands action (menu will be added later in init()) + m_insertAction = new Action(tr("&Insert"), this, QLatin1String("insert")); #ifndef KTIKZ_USE_KDE - menuBar()->insertAction(m_settingsMenu->menuAction(), m_insertAction); + menuBar()->insertAction(m_settingsMenu->menuAction(), m_insertAction); #endif - } + } - // add user commands menu + // add user commands menu #ifdef KTIKZ_USE_KDE - QMenu *userMenu = m_userCommandInserter->getMenu(); - QAction *userInsertAction = new Action(userMenu->title(), this, QLatin1String("user_insert")); - userInsertAction->setMenu(userMenu); + QMenu *userMenu = m_userCommandInserter->getMenu(); + QAction *userInsertAction = new Action(userMenu->title(), this, QLatin1String("user_insert")); + userInsertAction->setMenu(userMenu); #else - menuBar()->insertMenu(m_settingsMenu->menuAction(), m_userCommandInserter->getMenu()); + menuBar()->insertMenu(m_settingsMenu->menuAction(), m_userCommandInserter->getMenu()); #endif } void MainWindow::createStatusBar() { - QStatusBar *status = statusBar(); + QStatusBar *status = statusBar(); - m_positionLabel = new QLabel(status); - m_positionLabel->setMinimumWidth(150); - status->addPermanentWidget(m_positionLabel, 0); + m_positionLabel = new QLabel(status); + m_positionLabel->setMinimumWidth(150); + status->addPermanentWidget(m_positionLabel, 0); - m_mouseCoordinatesLabel = new QLabel(status); - m_mouseCoordinatesLabel->setMinimumWidth(300); - status->addPermanentWidget(m_mouseCoordinatesLabel, 0); + m_mouseCoordinatesLabel = new QLabel(status); + m_mouseCoordinatesLabel->setMinimumWidth(300); + status->addPermanentWidget(m_mouseCoordinatesLabel, 0); - status->showMessage(tr("Ready")); + status->showMessage(tr("Ready")); } void MainWindow::setDockWidgetStatusTip(bool enabled) { - QAction *action = qobject_cast(sender()); - QString dockName = action->text(); - dockName.remove(QLatin1Char('&')); - if (enabled) - action->setStatusTip(tr("Hide sidebar \"%1\"").arg(dockName)); - else - action->setStatusTip(tr("Show sidebar \"%1\"").arg(dockName)); + QAction *action = qobject_cast(sender()); + QString dockName = action->text(); + dockName.remove(QLatin1Char('&')); + if (enabled) + action->setStatusTip(tr("Hide sidebar \"%1\"").arg(dockName)); + else + action->setStatusTip(tr("Show sidebar \"%1\"").arg(dockName)); } void MainWindow::setToolBarStatusTip(bool enabled) { - QAction *action = qobject_cast(sender()); - if (enabled) - action->setStatusTip(tr("Hide toolbar \"%1\"").arg(action->text())); - else - action->setStatusTip(tr("Show toolbar \"%1\"").arg(action->text())); + QAction *action = qobject_cast(sender()); + if (enabled) + action->setStatusTip(tr("Hide toolbar \"%1\"").arg(action->text())); + else + action->setStatusTip(tr("Show toolbar \"%1\"").arg(action->text())); } /***************************************************************************/ void MainWindow::configure() { - if (!m_configDialog) - { - m_configDialog = new ConfigDialog(this); - m_configDialog->setTranslatedHighlightTypeNames(TikzHighlighter::getTranslatedHighlightTypeNames()); - m_configDialog->setHighlightTypeNames(TikzHighlighter::getHighlightTypeNames()); - m_configDialog->setDefaultHighlightFormats(TikzHighlighter::getDefaultHighlightFormats()); - connect(m_configDialog, SIGNAL(settingsChanged()), this, SLOT(applySettings())); - } - disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); - m_configDialog->readSettings(); - m_configDialog->exec(); - if (m_buildAutomatically) - connect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); + if (!m_configDialog) { + m_configDialog = new ConfigDialog(this); + m_configDialog->setTranslatedHighlightTypeNames( + TikzHighlighter::getTranslatedHighlightTypeNames()); + m_configDialog->setHighlightTypeNames(TikzHighlighter::getHighlightTypeNames()); + m_configDialog->setDefaultHighlightFormats(TikzHighlighter::getDefaultHighlightFormats()); + connect(m_configDialog, SIGNAL(settingsChanged()), this, SLOT(applySettings())); + } + disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); + m_configDialog->readSettings(); + m_configDialog->exec(); + if (m_buildAutomatically) + connect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); } void MainWindow::applySettings() { - QSettings settings; + QSettings settings; #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - m_tikzQtEditorView->applySettings(); - - m_tikzPreviewController->applySettings(); - - settings.beginGroup(QLatin1String("Preview")); - m_buildAutomatically = settings.value(QLatin1String("BuildAutomatically"), true).toBool(); - m_buildAction->setVisible(!m_buildAutomatically); - if (!settings.value(QLatin1String("ShowCoordinates"), true).toBool()) - m_mouseCoordinatesLabel->setText(QString()); - settings.endGroup(); - - settings.beginGroup(QLatin1String("Editor")); - m_useCompletion = settings.value(QLatin1String("UseCompletion"), true).toBool(); - updateCompleter(); - settings.beginGroup(QLatin1String("encoding")); - QVariant qv = settings.value(QLatin1String("default")); - setCurrentEncoding( qv.isNull() ? QTextCodec::codecForLocale() : QTextCodec::codecForName(qv.toByteArray())) ; - qv = settings.value(QLatin1String("encoder")); - m_overrideEncoder = qv.isNull() ? NULL : QTextCodec::codecForName(qv.toByteArray()) ; - qv = settings.value(QLatin1String("decoder")); - m_overrideDecoder = qv.isNull() ? NULL : QTextCodec::codecForName(qv.toByteArray()) ; - m_encoderBom = settings.value(QLatin1String("bom"), true).toBool(); - settings.endGroup(); + m_tikzQtEditorView->applySettings(); + + m_tikzPreviewController->applySettings(); + + settings.beginGroup(QLatin1String("Preview")); + m_buildAutomatically = settings.value(QLatin1String("BuildAutomatically"), true).toBool(); + m_buildAction->setVisible(!m_buildAutomatically); + if (!settings.value(QLatin1String("ShowCoordinates"), true).toBool()) + m_mouseCoordinatesLabel->setText(QString()); + settings.endGroup(); + + settings.beginGroup(QLatin1String("Editor")); + m_useCompletion = settings.value(QLatin1String("UseCompletion"), true).toBool(); + updateCompleter(); + settings.beginGroup(QLatin1String("encoding")); + QVariant qv = settings.value(QLatin1String("default")); + setCurrentEncoding(qv.isNull() ? QTextCodec::codecForLocale() + : QTextCodec::codecForName(qv.toByteArray())); + qv = settings.value(QLatin1String("encoder")); + m_overrideEncoder = qv.isNull() ? NULL : QTextCodec::codecForName(qv.toByteArray()); + qv = settings.value(QLatin1String("decoder")); + m_overrideDecoder = qv.isNull() ? NULL : QTextCodec::codecForName(qv.toByteArray()); + m_encoderBom = settings.value(QLatin1String("bom"), true).toBool(); + settings.endGroup(); #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - { - m_tikzHighlighter->applySettings(); - m_tikzHighlighter->rehighlight(); - } + { + m_tikzHighlighter->applySettings(); + m_tikzHighlighter->rehighlight(); + } - m_openRecentAction->createRecentFilesList(); + m_openRecentAction->createRecentFilesList(); #ifndef KTIKZ_USE_KDE - setToolBarStyle(); + setToolBarStyle(); #endif } void MainWindow::readSettings() { - m_openRecentAction->loadEntries(); - - QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - const int screenWidth = QApplication::desktop()->availableGeometry().width(); - QSize size; - if (screenWidth > 1200) - size = settings.value(QLatin1String("size"), QSize(1200, 600)).toSize(); - else if (screenWidth > 1024) - size = settings.value(QLatin1String("size"), QSize(1024, 600)).toSize(); - else - size = settings.value(QLatin1String("size"), QSize(800, 600)).toSize(); - resize(size); - restoreState(settings.value(QLatin1String("MainWindowState")).toByteArray()); - settings.endGroup(); - - // none of the problems below seem to persist in May 2014 - // still do the following (see applySettings()) here in order to avoid flicker in the toolbar -// settings.beginGroup(QLatin1String("Preview")); -// m_buildAutomatically = settings.value(QLatin1String("BuildAutomatically"), true).toBool(); -// m_buildAction->setVisible(!m_buildAutomatically); -// settings.endGroup(); - // still do the following here in order to avoid a crash when a file is opened in a new window -// m_openRecentAction->createRecentFilesList(); - // still do this here, otherwise the compilation fails when a file is loaded in a new window -// m_tikzPreviewController->applySettings(); + m_openRecentAction->loadEntries(); + + QSettings settings; + settings.beginGroup(QLatin1String("MainWindow")); + const int screenWidth = QApplication::desktop()->availableGeometry().width(); + QSize size; + if (screenWidth > 1200) + size = settings.value(QLatin1String("size"), QSize(1200, 600)).toSize(); + else if (screenWidth > 1024) + size = settings.value(QLatin1String("size"), QSize(1024, 600)).toSize(); + else + size = settings.value(QLatin1String("size"), QSize(800, 600)).toSize(); + resize(size); + restoreState(settings.value(QLatin1String("MainWindowState")).toByteArray()); + settings.endGroup(); + + // none of the problems below seem to persist in May 2014 + // still do the following (see applySettings()) here in order to avoid flicker in the toolbar + // settings.beginGroup(QLatin1String("Preview")); + // m_buildAutomatically = settings.value(QLatin1String("BuildAutomatically"), true).toBool(); + // m_buildAction->setVisible(!m_buildAutomatically); + // settings.endGroup(); + // still do the following here in order to avoid a crash when a file is opened in a new window + // m_openRecentAction->createRecentFilesList(); + // still do this here, otherwise the compilation fails when a file is loaded in a new window + // m_tikzPreviewController->applySettings(); } void MainWindow::writeSettings() { - m_openRecentAction->saveEntries(); + m_openRecentAction->saveEntries(); - QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); - settings.setValue(QLatin1String("size"), size()); - settings.setValue(QLatin1String("MainWindowState"), QMainWindow::saveState()); - settings.endGroup(); + QSettings settings; + settings.beginGroup(QLatin1String("MainWindow")); + settings.setValue(QLatin1String("size"), size()); + settings.setValue(QLatin1String("MainWindowState"), QMainWindow::saveState()); + settings.endGroup(); } /***************************************************************************/ bool MainWindow::maybeSave() { - checkForFileChanges(Closing); - if (m_isModifiedExternally) // if the user presses "Cancel" when asked to overwrite or close the file, then we abort the closing procedure - return false; - if (m_tikzEditorView->isModified()) - { - const int ret = QMessageBox::warning(this, KtikzApplication::applicationName(), - tr("The document has been modified.\n" - "Do you want to save your changes?"), - QMessageBox::Save | QMessageBox::Default, - QMessageBox::Discard, - QMessageBox::Cancel | QMessageBox::Escape); - if (ret == QMessageBox::Save) - return save(); - else if (ret == QMessageBox::Cancel) - return false; - } - return true; + checkForFileChanges(Closing); + if (m_isModifiedExternally) // if the user presses "Cancel" when asked to overwrite or close the + // file, then we abort the closing procedure + return false; + if (m_tikzEditorView->isModified()) { + const int ret = + QMessageBox::warning(this, KtikzApplication::applicationName(), + tr("The document has been modified.\n" + "Do you want to save your changes?"), + QMessageBox::Save | QMessageBox::Default, QMessageBox::Discard, + QMessageBox::Cancel | QMessageBox::Escape); + if (ret == QMessageBox::Save) + return save(); + else if (ret == QMessageBox::Cancel) + return false; + } + return true; } void MainWindow::loadUrl(const QUrl &url) { -// loadUrl(Url(url)); -//} - -//void MainWindow::loadUrl(const Url &url) -//{ -//QTime t = QTime::currentTime(); - // check whether the file can be opened - if (!url.isValid() || url.isEmpty()) - return; - - File file(url, File::ReadOnly); - if (!file.open(QFile::Text)) - { - QMessageBox::warning(this, KtikzApplication::applicationName(), - tr("Cannot read file \"%1\":\n%2.") - .arg(url.path()) - .arg(file.errorString())); - m_openRecentAction->removeUrl(url); - return; - } - - // only open a new window (if necessary) if the file can actually be opened - if (!m_tikzEditorView->isEmpty()) - { - MainWindow *newMainWindow = new MainWindow; - newMainWindow->loadUrl(url); - newMainWindow->show(); - return; - } - - // set current url before loading its contents in m_tikzEditorView->editor() - // because this latter action causes m_tikzPreviewController->generatePreview() - // to be called which calls url() - setCurrentUrl(url); - - // load the file and generate preview -//qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); - disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); + // loadUrl(Url(url)); + //} + + // void MainWindow::loadUrl(const Url &url) + //{ + // QTime t = QTime::currentTime(); + // check whether the file can be opened + if (!url.isValid() || url.isEmpty()) + return; + + File file(url, File::ReadOnly); + if (!file.open(QFile::Text)) { + QMessageBox::warning( + this, KtikzApplication::applicationName(), + tr("Cannot read file \"%1\":\n%2.").arg(url.path()).arg(file.errorString())); + m_openRecentAction->removeUrl(url); + return; + } + + // only open a new window (if necessary) if the file can actually be opened + if (!m_tikzEditorView->isEmpty()) { + MainWindow *newMainWindow = new MainWindow; + newMainWindow->loadUrl(url); + newMainWindow->show(); + return; + } + + // set current url before loading its contents in m_tikzEditorView->editor() + // because this latter action causes m_tikzPreviewController->generatePreview() + // to be called which calls url() + setCurrentUrl(url); + + // load the file and generate preview + // qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); + disconnect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); #ifdef KTIKZ_USE_KTEXTEDITOR - if (m_useKTextEditor) - { - m_tikzKTextEditor->document()->openUrl(url); - } - else + if (m_useKTextEditor) { + m_tikzKTextEditor->document()->openUrl(url); + } else #endif - { - QTextStream in(file.file()); - QApplication::setOverrideCursor(Qt::WaitCursor); - this->configureStreamDecoding(in); - m_tikzQtEditorView->editor()->setPlainText(in.readAll()); - setCurrentEncoding(in.codec()); - } - - QApplication::restoreOverrideCursor(); -//qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); - m_tikzPreviewController->generatePreview(); -//qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); - if (m_buildAutomatically) - connect(m_tikzEditorView, SIGNAL(contentsChanged()), - m_tikzPreviewController, SLOT(regeneratePreviewAfterDelay())); - - m_lastUrl = url; - m_openRecentAction->addUrl(url); -//qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); -// statusBar()->showMessage(tr("File loaded"), 2000); // this is slow -// statusBar()->showMessage(tr("File loaded using %1 codec").arg(QString( m_currentEncoding->name())), 2000); -//qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); + { + QTextStream in(file.file()); + QApplication::setOverrideCursor(Qt::WaitCursor); + this->configureStreamDecoding(in); + m_tikzQtEditorView->editor()->setPlainText(in.readAll()); + setCurrentEncoding(in.codec()); + } + + QApplication::restoreOverrideCursor(); + // qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); + m_tikzPreviewController->generatePreview(); + // qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); + if (m_buildAutomatically) + connect(m_tikzEditorView, SIGNAL(contentsChanged()), m_tikzPreviewController, + SLOT(regeneratePreviewAfterDelay())); + + m_lastUrl = url; + m_openRecentAction->addUrl(url); + // qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); + // statusBar()->showMessage(tr("File loaded"), 2000); // this is slow + // statusBar()->showMessage(tr("File loaded using %1 codec").arg(QString( + // m_currentEncoding->name())), 2000); + // qCritical() << "loadUrl" << t.msecsTo(QTime::currentTime()); } void MainWindow::changedUrl(const QUrl &url) { - setCurrentUrl(url); + setCurrentUrl(url); } bool MainWindow::saveUrl(const QUrl &url) { - if (!url.isValid() || url.isEmpty()) - return false; - - File file(url, File::WriteOnly); - if (!file.open(QFile::Text)) - { - QMessageBox::warning(this, KtikzApplication::applicationName(), - tr("Cannot write file \"%1\":\n%2") - .arg(url.path()) - .arg(file.errorString())); - return false; - } - - QTextStream out(file.file()); - QApplication::setOverrideCursor(Qt::WaitCursor); - - this->configureStreamEncoding(out); - out << m_tikzEditorView->text(); - out.flush(); - QApplication::restoreOverrideCursor(); - - if (!file.close()) - { - QMessageBox::warning(this, KtikzApplication::applicationName(), - tr("Cannot write file \"%1\":\n%2") - .arg(url.path()) - .arg(file.errorString())); - return false; - } - - m_lastUrl = url; - setCurrentUrl(url); - m_openRecentAction->addUrl(url); - saveLastInternalModifiedDateTime(); // make sure that the save in this function is not seen as an "external" save - statusBar()->showMessage(tr("File saved", "@info:status"), 2000); - return true; + if (!url.isValid() || url.isEmpty()) + return false; + + File file(url, File::WriteOnly); + if (!file.open(QFile::Text)) { + QMessageBox::warning( + this, KtikzApplication::applicationName(), + tr("Cannot write file \"%1\":\n%2").arg(url.path()).arg(file.errorString())); + return false; + } + + QTextStream out(file.file()); + QApplication::setOverrideCursor(Qt::WaitCursor); + + this->configureStreamEncoding(out); + out << m_tikzEditorView->text(); + out.flush(); + QApplication::restoreOverrideCursor(); + + if (!file.close()) { + QMessageBox::warning( + this, KtikzApplication::applicationName(), + tr("Cannot write file \"%1\":\n%2").arg(url.path()).arg(file.errorString())); + return false; + } + + m_lastUrl = url; + setCurrentUrl(url); + m_openRecentAction->addUrl(url); + saveLastInternalModifiedDateTime(); // make sure that the save in this function is not seen as + // an "external" save + statusBar()->showMessage(tr("File saved", "@info:status"), 2000); + return true; } -void MainWindow::setCurrentEncoding(QTextCodec *codec ) +void MainWindow::setCurrentEncoding(QTextCodec *codec) { - m_currentEncoding = codec; - // TODO: implement user warning and suggestion to reload the file. + m_currentEncoding = codec; + // TODO: implement user warning and suggestion to reload the file. } QUrl MainWindow::url() const { - return m_currentUrl; + return m_currentUrl; } void MainWindow::setCurrentUrl(const QUrl &url) { - m_currentUrl = url; + m_currentUrl = url; m_tikzEditorView->setModified(false); - setDocumentModified(false); - setWindowTitle(tr("%1[*] - %2").arg(strippedName(m_currentUrl)).arg(KtikzApplication::applicationName())); + setDocumentModified(false); + setWindowTitle(tr("%1[*] - %2") + .arg(strippedName(m_currentUrl)) + .arg(KtikzApplication::applicationName())); } QString MainWindow::strippedName(const QUrl &url) const { - if (!url.isValid() || url.isEmpty()) - return QLatin1String("untitled.txt"); - const QString fileName = url.fileName(); - return (fileName.isEmpty()) ? QLatin1String("untitled.txt") : fileName; + if (!url.isValid() || url.isEmpty()) + return QLatin1String("untitled.txt"); + const QString fileName = url.fileName(); + return (fileName.isEmpty()) ? QLatin1String("untitled.txt") : fileName; } QTextCodec *MainWindow::getEncoder() const { - return this->m_overrideEncoder ? this->m_overrideEncoder : this->m_currentEncoding; + return this->m_overrideEncoder ? this->m_overrideEncoder : this->m_currentEncoding; } -void MainWindow::configureStreamEncoding(QTextStream& textStream) +void MainWindow::configureStreamEncoding(QTextStream &textStream) { - QTextCodec* encoder = this->getEncoder(); - if(Q_LIKELY(encoder)) // should be true - textStream.setCodec(encoder); - else - qWarning("The encoder variable should not be null."); - - textStream.setGenerateByteOrderMark(this->m_encoderBom); + QTextCodec *encoder = this->getEncoder(); + if (Q_LIKELY(encoder)) // should be true + textStream.setCodec(encoder); + else + qWarning("The encoder variable should not be null."); + textStream.setGenerateByteOrderMark(this->m_encoderBom); } void MainWindow::configureStreamDecoding(QTextStream &textStream) { - if(m_overrideDecoder) - { - textStream.setCodec(m_overrideDecoder); - } - textStream.setAutoDetectUnicode(true); + if (m_overrideDecoder) { + textStream.setCodec(m_overrideDecoder); + } + textStream.setAutoDetectUnicode(true); } /***************************************************************************/ @@ -1160,49 +1182,53 @@ void MainWindow::configureStreamDecoding(QTextStream &textStream) void MainWindow::setLineNumber(int lineNumber) { #ifdef KTIKZ_USE_KTEXTEDITOR - if (!m_useKTextEditor) + if (!m_useKTextEditor) #endif - m_tikzQtEditorView->goToLine(lineNumber - 1); + m_tikzQtEditorView->goToLine(lineNumber - 1); } int MainWindow::lineNumber() const { #ifdef KTIKZ_USE_KTEXTEDITOR - if (m_useKTextEditor) - return 0; //TODO: do something - else + if (m_useKTextEditor) + return 0; // TODO: do something + else #endif - return m_tikzQtEditorView->lineNumber(); + return m_tikzQtEditorView->lineNumber(); } /***************************************************************************/ void MainWindow::showCursorPosition(int row, int col) { - m_positionLabel->setText(tr("Line: %1\tCol: %2", "@info:status").arg(QString::number(row)).arg(QString::number(col))); + m_positionLabel->setText(tr("Line: %1\tCol: %2", "@info:status") + .arg(QString::number(row)) + .arg(QString::number(col))); } void MainWindow::showMouseCoordinates(qreal x, qreal y, int precisionX, int precisionY) { - m_mouseCoordinatesLabel->setText(tr("Preview: x = %1\ty = %2", "@info:status").arg(QLocale::system().toString(x, 'f', precisionX)).arg(QLocale::system().toString(y, 'f', precisionY))); + m_mouseCoordinatesLabel->setText(tr("Preview: x = %1\ty = %2", "@info:status") + .arg(QLocale::system().toString(x, 'f', precisionX)) + .arg(QLocale::system().toString(y, 'f', precisionY))); } /***************************************************************************/ QString MainWindow::tikzCode() const { - return m_tikzEditorView->text(); + return m_tikzEditorView->text(); } /***************************************************************************/ void MainWindow::updateCompleter() { -//QTime t = QTime::currentTime(); - QStringList words = m_commandInserter->getCommandWords(); - words << m_userCommandInserter->getCommandWords(); - words.sort(); - words.removeDuplicates(); - m_tikzEditorView->updateCompleter(m_useCompletion, words); -//qCritical() << "updateCompleter" << t.msecsTo(QTime::currentTime()); + // QTime t = QTime::currentTime(); + QStringList words = m_commandInserter->getCommandWords(); + words << m_userCommandInserter->getCommandWords(); + words.sort(); + words.removeDuplicates(); + m_tikzEditorView->updateCompleter(m_useCompletion, words); + // qCritical() << "updateCompleter" << t.msecsTo(QTime::currentTime()); } diff --git a/app/mainwindow.h b/app/mainwindow.h index a477c1e..04f4dee 100644 --- a/app/mainwindow.h +++ b/app/mainwindow.h @@ -24,10 +24,10 @@ #define MAINWINDOW_H #ifdef KTIKZ_USE_KDE -#include +# include #else -#include -#include +# include +# include class AboutDialog; class AssistantController; @@ -65,182 +65,179 @@ class MainWindow : public KXmlGuiWindow, public MainWidget class MainWindow : public QMainWindow, public MainWidget #endif { - Q_OBJECT + Q_OBJECT public: - /*! - * This enum is used to determine when the file is checked for external changes. - */ - enum FileCheckMoment - { - FocusIn, /*! mainWindowList() - { - return s_mainWindowList; - } - - virtual void configureStreamEncoding(QTextStream &textStream); - virtual void configureStreamDecoding(QTextStream &textStream); + /*! + * This enum is used to determine when the file is checked for external changes. + */ + enum FileCheckMoment { + FocusIn, /*! mainWindowList() { return s_mainWindowList; } + + virtual void configureStreamEncoding(QTextStream &textStream); + virtual void configureStreamDecoding(QTextStream &textStream); public Q_SLOTS: - void loadUrl(const QUrl &url); - void changedUrl(const QUrl &url); - bool save(); + void loadUrl(const QUrl &url); + void changedUrl(const QUrl &url); + bool save(); protected: #ifdef KTIKZ_USE_KDE - bool queryClose(); - void readProperties(const KConfigGroup &group); - void saveProperties(KConfigGroup &group); + bool queryClose(); + void readProperties(const KConfigGroup &group); + void saveProperties(KConfigGroup &group); #endif - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event); private Q_SLOTS: - void init(); - void checkForFileChanges(const FileCheckMoment &moment = FocusIn); - void saveLastInternalModifiedDateTime(); - void setDockWidgetStatusTip(bool enabled); - void setToolBarStatusTip(bool enabled); - void newFile(); - bool closeFile(); - void open(); - bool saveAs(); - void reload(); - void showTikzDocumentation(); + void init(); + void checkForFileChanges(const FileCheckMoment &moment = FocusIn); + void saveLastInternalModifiedDateTime(); + void setDockWidgetStatusTip(bool enabled); + void setToolBarStatusTip(bool enabled); + void newFile(); + bool closeFile(); + void open(); + bool saveAs(); + void reload(); + void showTikzDocumentation(); #ifndef KTIKZ_USE_KDE - void about(); - void showDocumentation(); + void about(); + void showDocumentation(); #endif - void configure(); - void applySettings(); - void setDocumentModified(bool isModified); - void updateLog(); + void configure(); + void applySettings(); + void setDocumentModified(bool isModified); + void updateLog(); #ifdef KTIKZ_USE_KDE - void toggleWhatsThisMode(); + void toggleWhatsThisMode(); #endif - void showCursorPosition(int row, int col); - void showMouseCoordinates(qreal x, qreal y, int precisionX = 5, int precisionY = 5); - void updateCompleter(); - /// Change the codec for the current document - /// @param isUserRequest set to true if the user requested the changement (in this case, the application should warn the user -- not implemented yet.). - void setCurrentEncoding(QTextCodec* codec /*, bool isUserRequest = false */ ); + void showCursorPosition(int row, int col); + void showMouseCoordinates(qreal x, qreal y, int precisionX = 5, int precisionY = 5); + void updateCompleter(); + /// Change the codec for the current document + /// @param isUserRequest set to true if the user requested the changement (in this case, the + /// application should warn the user -- not implemented yet.). + void setCurrentEncoding(QTextCodec *codec /*, bool isUserRequest = false */); private: - void createActions(); + void createActions(); #ifdef KTIKZ_USE_KDE - void addActionCloneToCollection(const QString &actionName, QAction *action); + void addActionCloneToCollection(const QString &actionName, QAction *action); #else - void createMenus(); - void createToolBars(); - void setToolBarStyle(); + void createMenus(); + void createToolBars(); + void setToolBarStyle(); #endif - void createCommandInsertWidget(); - void createStatusBar(); - void readSettings(); - void writeSettings(); - bool maybeSave(); - bool saveUrl(const QUrl &url); - void setCurrentUrl(const QUrl &url); - QString strippedName(const QUrl &url) const; - void showPdfPage(); - - static QList s_mainWindowList; - - bool m_useKTextEditor; - TikzEditorViewAbstract *m_tikzEditorView; + void createCommandInsertWidget(); + void createStatusBar(); + void readSettings(); + void writeSettings(); + bool maybeSave(); + bool saveUrl(const QUrl &url); + void setCurrentUrl(const QUrl &url); + QString strippedName(const QUrl &url) const; + void showPdfPage(); + + static QList s_mainWindowList; + + bool m_useKTextEditor; + TikzEditorViewAbstract *m_tikzEditorView; #ifdef KTIKZ_USE_KTEXTEDITOR - TikzKTextEditorView *m_tikzKTextEditor; + TikzKTextEditorView *m_tikzKTextEditor; #endif - TikzEditorView *m_tikzQtEditorView; - TikzHighlighter *m_tikzHighlighter; - - bool m_useCompletion; - - TikzPreviewController *m_tikzPreviewController; - bool m_buildAutomatically; - - QDockWidget *m_previewDock; - - QDockWidget *m_logDock; - LogTextEdit *m_logTextEdit; - - QDockWidget *m_commandsDock; - TikzCommandInserter *m_commandInserter; - UserCommandInserter *m_userCommandInserter; - - QLabel *m_positionLabel; - QLabel *m_mouseCoordinatesLabel; - - QMenu *m_settingsMenu; - QMenu *m_sideBarMenu; - QToolBar *m_fileToolBar; - QToolBar *m_editToolBar; - QToolBar *m_viewToolBar; - QToolBar *m_runToolBar; -//#ifndef KTIKZ_USE_KTEXTEDITOR - QAction *m_saveAction; - QAction *m_saveAsAction; - Action *m_reloadAction; -//#endif - QAction *m_newAction; - QAction *m_openAction; - RecentFilesAction *m_openRecentAction; - QAction *m_exportAction; - QAction *m_exportEpsAction; - QAction *m_exportPdfAction; - QAction *m_exportPngAction; - QAction *m_closeAction; - QAction *m_exitAction; - QAction *m_procStopAction; - Action *m_buildAction; - Action *m_insertAction; - QAction *m_viewLogAction; - QAction *m_shellEscapeAction; - QAction *m_configureAction; - QAction *m_showTikzDocAction; - QAction *m_whatsThisAction; + TikzEditorView *m_tikzQtEditorView; + TikzHighlighter *m_tikzHighlighter; + + bool m_useCompletion; + + TikzPreviewController *m_tikzPreviewController; + bool m_buildAutomatically; + + QDockWidget *m_previewDock; + + QDockWidget *m_logDock; + LogTextEdit *m_logTextEdit; + + QDockWidget *m_commandsDock; + TikzCommandInserter *m_commandInserter; + UserCommandInserter *m_userCommandInserter; + + QLabel *m_positionLabel; + QLabel *m_mouseCoordinatesLabel; + + QMenu *m_settingsMenu; + QMenu *m_sideBarMenu; + QToolBar *m_fileToolBar; + QToolBar *m_editToolBar; + QToolBar *m_viewToolBar; + QToolBar *m_runToolBar; + // #ifndef KTIKZ_USE_KTEXTEDITOR + QAction *m_saveAction; + QAction *m_saveAsAction; + Action *m_reloadAction; + // #endif + QAction *m_newAction; + QAction *m_openAction; + RecentFilesAction *m_openRecentAction; + QAction *m_exportAction; + QAction *m_exportEpsAction; + QAction *m_exportPdfAction; + QAction *m_exportPngAction; + QAction *m_closeAction; + QAction *m_exitAction; + QAction *m_procStopAction; + Action *m_buildAction; + Action *m_insertAction; + QAction *m_viewLogAction; + QAction *m_shellEscapeAction; + QAction *m_configureAction; + QAction *m_showTikzDocAction; + QAction *m_whatsThisAction; #ifndef KTIKZ_USE_KDE - QAction *m_helpAction; - QAction *m_aboutAction; - QAction *m_aboutQtAction; + QAction *m_helpAction; + QAction *m_aboutAction; + QAction *m_aboutQtAction; #endif - QToolButton *m_shellEscapeButton; - bool m_useShellEscaping; + QToolButton *m_shellEscapeButton; + bool m_useShellEscaping; #ifndef KTIKZ_USE_KDE - QPointer m_aboutDialog; - AssistantController *m_assistantController; + QPointer m_aboutDialog; + AssistantController *m_assistantController; #endif - QPointer m_configDialog; - - QUrl m_currentUrl; - QTextCodec* m_currentEncoding; - /// If not null, override the encoder (rather than @ref m_currentEncoding) - QTextCodec* m_overrideEncoder; - /// If not null, override the decoder - QTextCodec* m_overrideDecoder; - /// True if a BOM must be added to the PGF-file - bool m_encoderBom; - /// Return the current encoder (m_currentEncoding or another if encoder is overriden). - /*virtual*/ QTextCodec* getEncoder() const; - - QUrl m_lastUrl; - QDateTime m_lastInternalModifiedDateTime; - bool m_isModifiedExternally; + QPointer m_configDialog; + + QUrl m_currentUrl; + QTextCodec *m_currentEncoding; + /// If not null, override the encoder (rather than @ref m_currentEncoding) + QTextCodec *m_overrideEncoder; + /// If not null, override the decoder + QTextCodec *m_overrideDecoder; + /// True if a BOM must be added to the PGF-file + bool m_encoderBom; + /// Return the current encoder (m_currentEncoding or another if encoder is overriden). + /*virtual*/ QTextCodec *getEncoder() const; + + QUrl m_lastUrl; + QDateTime m_lastInternalModifiedDateTime; + bool m_isModifiedExternally; }; #endif diff --git a/app/tikzcommandinserter.cpp b/app/tikzcommandinserter.cpp index 3aabb8a..79f4ab6 100644 --- a/app/tikzcommandinserter.cpp +++ b/app/tikzcommandinserter.cpp @@ -19,9 +19,9 @@ #include "tikzcommandinserter.h" #ifdef KTIKZ_USE_KTEXTEDITOR -#include -#include -#include +# include +# include +# include #endif #include @@ -52,295 +52,317 @@ TikzCommandList TikzCommandInserter::m_tikzSections; QList TikzCommandInserter::m_tikzCommandsList; TikzCommandInserter::TikzCommandInserter(QWidget *parent) - : QObject(parent) + : QObject(parent) #ifdef KTIKZ_USE_KTEXTEDITOR - , m_mainKFEdit(0) + , + m_mainKFEdit(0) #endif - , m_mainEdit(0) - , m_commandsCombo(0) - , m_commandsStack(0) + , + m_mainEdit(0), + m_commandsCombo(0), + m_commandsStack(0) { } /***************************************************************************/ -static TikzCommand newCommand(const QString &name, - const QString &description, const QString &command, - const QString &highlightString, int dx, int dy, int type) +static TikzCommand newCommand(const QString &name, const QString &description, + const QString &command, const QString &highlightString, int dx, + int dy, int type) { - // type: - // 0: plain text - // 1: command - // 2: draw to next point - // 3: option - TikzCommand tikzCommand; - tikzCommand.name = name; - tikzCommand.description = description; - tikzCommand.command = command; - tikzCommand.highlightString = highlightString; - tikzCommand.dx = dx; - tikzCommand.dy = dy; - tikzCommand.type = type; - - return tikzCommand; + // type: + // 0: plain text + // 1: command + // 2: draw to next point + // 3: option + TikzCommand tikzCommand; + tikzCommand.name = name; + tikzCommand.description = description; + tikzCommand.command = command; + tikzCommand.highlightString = highlightString; + tikzCommand.dx = dx; + tikzCommand.dy = dy; + tikzCommand.type = type; + + return tikzCommand; } static QString translateOptions(const QString &text) { - QString translatedText; - for (int pos = 0, oldPos = 0; pos >= 0;) - { - oldPos = pos; - pos = text.indexOf(QLatin1Char('<'), pos); // option is between < and > - translatedText += text.midRef(oldPos, pos - oldPos + 1); // add text between the current option and the previous option; this also adds the end of the original string, except when there are no options - if (pos >= 0) - { - oldPos = pos; - pos = text.indexOf(QLatin1Char('>'), pos); // option is between < and > - translatedText += QCoreApplication::translate("TikzCommandInserter", text.mid(oldPos+1, pos - oldPos - 1).toLatin1().data()); - } - } - if (!translatedText.isEmpty()) // when there are no options, translatedText is empty - return translatedText; - return text; + QString translatedText; + for (int pos = 0, oldPos = 0; pos >= 0;) { + oldPos = pos; + pos = text.indexOf(QLatin1Char('<'), pos); // option is between < and > + translatedText += text.midRef( + oldPos, pos - oldPos + 1); // add text between the current option and the previous + // option; this also adds the end of the original string, + // except when there are no options + if (pos >= 0) { + oldPos = pos; + pos = text.indexOf(QLatin1Char('>'), pos); // option is between < and > + translatedText += QCoreApplication::translate( + "TikzCommandInserter", + text.mid(oldPos + 1, pos - oldPos - 1).toLatin1().data()); + } + } + if (!translatedText.isEmpty()) // when there are no options, translatedText is empty + return translatedText; + return text; } static QString restoreNewLines(const QString &text) { - QString newText = text; - // replace all "\n" not preceded by a backslash (as in "\\node") by a newline character - for (int pos = 0; ; ++pos) - { - pos = newText.indexOf(QLatin1String("\\n"), pos); - if (pos < 0) - break; - if (pos == 0 || newText.at(pos-1) != QLatin1Char('\\')) - newText.replace(pos, 2, QLatin1Char('\n')); - } - return newText; + QString newText = text; + // replace all "\n" not preceded by a backslash (as in "\\node") by a newline character + for (int pos = 0;; ++pos) { + pos = newText.indexOf(QLatin1String("\\n"), pos); + if (pos < 0) + break; + if (pos == 0 || newText.at(pos - 1) != QLatin1Char('\\')) + newText.replace(pos, 2, QLatin1Char('\n')); + } + return newText; } static TikzCommandList getChildCommands(QXmlStreamReader *xml, QList *tikzCommandsList) { - TikzCommandList commandList; - QList commands; - - commandList.title = QApplication::translate("TikzCommandInserter", xml->attributes().value(QLatin1String("title")).toString().toLatin1().data()); - - while (xml->readNextStartElement()) - { - if (xml->name() == QLatin1String("item")) - { - QXmlStreamAttributes xmlAttributes = xml->attributes(); - QString name = QApplication::translate("TikzCommandInserter", xmlAttributes.value(QLatin1String("name")).toString().toLatin1().data()); - QString description = xmlAttributes.value(QLatin1String("description")).toString(); - QString insertion = xmlAttributes.value(QLatin1String("insert")).toString(); - QString highlightString = xmlAttributes.value(QLatin1String("highlight")).toString(); - QString type = xmlAttributes.value(QLatin1String("type")).toString(); - - // currently description contains no newlines, otherwise add code to replace all "\n" not preceded by a backslash (as in "\\node") by a newline character - description.replace(QLatin1String("\\\\"), QLatin1String("\\")); - description = translateOptions(description); - - insertion = restoreNewLines(insertion); // this must be done before the next line - insertion.replace(QLatin1String("\\\\"), QLatin1String("\\")); - - if (description.isEmpty()) // if both name and description are empty, setting the description first ensures that name is also set to insertion - description = insertion; - if (name.isEmpty()) - { - name = description; - description.remove(QLatin1Char('&')); // we assume that if name.isEmpty() then an accelerator is defined in description - } - if (type.isEmpty()) - type = QLatin1Char('0'); - - TikzCommand tikzCommand = newCommand(name, description, insertion, highlightString, xmlAttributes.value(QLatin1String("dx")).toString().toInt(), xmlAttributes.value(QLatin1String("dy")).toString().toInt(), type.toInt()); - tikzCommand.number = tikzCommandsList->size(); - tikzCommandsList->append(tikzCommand); - commands << tikzCommand; - xml->skipCurrentElement(); // allow to read the next start element on the same level: this skips reading the current end element which would cause xml.readNextStartElement() to evaluate to false - } - else if (xml->name() == QLatin1String("separator")) - { - commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, 0); - xml->skipCurrentElement(); // same as above - } - else if (xml->name() == QLatin1String("section")) - { - commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, -1); // the i-th command with type == -1 corresponds to the i-th submenu (assumed in getMenu()) - commandList.children << getChildCommands(xml, tikzCommandsList); - } - else - xml->skipCurrentElement(); - } - commandList.commands = commands; - - return commandList; + TikzCommandList commandList; + QList commands; + + commandList.title = QApplication::translate( + "TikzCommandInserter", + xml->attributes().value(QLatin1String("title")).toString().toLatin1().data()); + + while (xml->readNextStartElement()) { + if (xml->name() == QLatin1String("item")) { + QXmlStreamAttributes xmlAttributes = xml->attributes(); + QString name = QApplication::translate( + "TikzCommandInserter", + xmlAttributes.value(QLatin1String("name")).toString().toLatin1().data()); + QString description = xmlAttributes.value(QLatin1String("description")).toString(); + QString insertion = xmlAttributes.value(QLatin1String("insert")).toString(); + QString highlightString = xmlAttributes.value(QLatin1String("highlight")).toString(); + QString type = xmlAttributes.value(QLatin1String("type")).toString(); + + // currently description contains no newlines, otherwise add code to replace all "\n" + // not preceded by a backslash (as in "\\node") by a newline character + description.replace(QLatin1String("\\\\"), QLatin1String("\\")); + description = translateOptions(description); + + insertion = restoreNewLines(insertion); // this must be done before the next line + insertion.replace(QLatin1String("\\\\"), QLatin1String("\\")); + + if (description + .isEmpty()) // if both name and description are empty, setting the + // description first ensures that name is also set to insertion + description = insertion; + if (name.isEmpty()) { + name = description; + description.remove(QLatin1Char('&')); // we assume that if name.isEmpty() then an + // accelerator is defined in description + } + if (type.isEmpty()) + type = QLatin1Char('0'); + + TikzCommand tikzCommand = newCommand( + name, description, insertion, highlightString, + xmlAttributes.value(QLatin1String("dx")).toString().toInt(), + xmlAttributes.value(QLatin1String("dy")).toString().toInt(), type.toInt()); + tikzCommand.number = tikzCommandsList->size(); + tikzCommandsList->append(tikzCommand); + commands << tikzCommand; + xml->skipCurrentElement(); // allow to read the next start element on the same level: + // this skips reading the current end element which would + // cause xml.readNextStartElement() to evaluate to false + } else if (xml->name() == QLatin1String("separator")) { + commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, 0); + xml->skipCurrentElement(); // same as above + } else if (xml->name() == QLatin1String("section")) { + commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, + -1); // the i-th command with type == -1 corresponds to the i-th + // submenu (assumed in getMenu()) + commandList.children << getChildCommands(xml, tikzCommandsList); + } else + xml->skipCurrentElement(); + } + commandList.commands = commands; + + return commandList; } -static TikzCommandList loadChildCommandsJson(QJsonObject sectionObject, QList *tikzCommandsList) +static TikzCommandList loadChildCommandsJson(QJsonObject sectionObject, + QList *tikzCommandsList) { - TikzCommandList commandList; - QList commands; - - if (sectionObject.contains(QLatin1String("title"))) - commandList.title = QCoreApplication::translate("TikzCommandInserter", sectionObject.value(QLatin1String("title")).toString().toLatin1().data()); - - if (sectionObject.contains(QLatin1String("commands"))) - { - QJsonValue commandsArrayObject = sectionObject.value(QLatin1String("commands")); - if (commandsArrayObject.isArray()) - { - QJsonArray commandsArray = commandsArrayObject.toArray(); - for (int i = 0; i < commandsArray.size(); ++i) - { - if (!commandsArray.at(i).isObject()) - continue; - QJsonObject commandObject = commandsArray.at(i).toObject(); - const int type = commandObject.value(QLatin1String("type")).toInt(); - if (commandObject.contains(QLatin1String("commands"))) - { - commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, -1); // the i-th command with type == -1 corresponds to the i-th submenu (assumed in getMenu()) - commandList.children << loadChildCommandsJson(commandObject, tikzCommandsList); - } - else if (type == -1) - { - commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, 0); - } - else - { - QString name = QCoreApplication::translate("TikzCommandInserter", commandObject.value(QLatin1String("name")).toString().toLatin1().data()); - QString description = commandObject.value(QLatin1String("description")).toString(); - QString insertion = commandObject.value(QLatin1String("insert")).toString(); - QString highlightString = commandObject.value(QLatin1String("highlight")).toString(); - - // currently description contains no newlines, otherwise add code to replace all "\n" not preceded by a backslash (as in "\\node") by a newline character - description.replace(QLatin1String("\\\\"), QLatin1String("\\")); - description = translateOptions(description); - - insertion = restoreNewLines(insertion); // this must be done before the next line - insertion.replace(QLatin1String("\\\\"), QLatin1String("\\")); -// insertion.replace(QLatin1String("•"), QString(0x2022)); - - if (description.isEmpty()) // if both name and description are empty, setting the description first ensures that name is also set to insertion - description = insertion; - if (name.isEmpty()) - { - name = description; - description.remove(QLatin1Char('&')); // we assume that if name.isEmpty() then an accelerator is defined in description - } - - TikzCommand tikzCommand = newCommand(name, description, insertion, highlightString, commandObject.value(QLatin1String("dx")).toInt(), commandObject.value(QLatin1String("dy")).toInt(), type); - tikzCommand.number = tikzCommandsList->size(); - tikzCommandsList->append(tikzCommand); - commands << tikzCommand; - } - } - } - } - commandList.commands = commands; - - return commandList; + TikzCommandList commandList; + QList commands; + + if (sectionObject.contains(QLatin1String("title"))) + commandList.title = QCoreApplication::translate( + "TikzCommandInserter", + sectionObject.value(QLatin1String("title")).toString().toLatin1().data()); + + if (sectionObject.contains(QLatin1String("commands"))) { + QJsonValue commandsArrayObject = sectionObject.value(QLatin1String("commands")); + if (commandsArrayObject.isArray()) { + QJsonArray commandsArray = commandsArrayObject.toArray(); + for (int i = 0; i < commandsArray.size(); ++i) { + if (!commandsArray.at(i).isObject()) + continue; + QJsonObject commandObject = commandsArray.at(i).toObject(); + const int type = commandObject.value(QLatin1String("type")).toInt(); + if (commandObject.contains(QLatin1String("commands"))) { + commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, + -1); // the i-th command with type == -1 corresponds to + // the i-th submenu (assumed in getMenu()) + commandList.children << loadChildCommandsJson(commandObject, tikzCommandsList); + } else if (type == -1) { + commands << newCommand(QString(), QString(), QString(), QString(), 0, 0, 0); + } else { + QString name = + QCoreApplication::translate("TikzCommandInserter", + commandObject.value(QLatin1String("name")) + .toString() + .toLatin1() + .data()); + QString description = + commandObject.value(QLatin1String("description")).toString(); + QString insertion = commandObject.value(QLatin1String("insert")).toString(); + QString highlightString = + commandObject.value(QLatin1String("highlight")).toString(); + + // currently description contains no newlines, otherwise add code to replace all + // "\n" not preceded by a backslash (as in "\\node") by a newline character + description.replace(QLatin1String("\\\\"), QLatin1String("\\")); + description = translateOptions(description); + + insertion = + restoreNewLines(insertion); // this must be done before the next line + insertion.replace(QLatin1String("\\\\"), QLatin1String("\\")); + // insertion.replace(QLatin1String("•"), + //QString(0x2022)); + + if (description.isEmpty()) // if both name and description are empty, setting + // the description first ensures that name is also + // set to insertion + description = insertion; + if (name.isEmpty()) { + name = description; + description.remove( + QLatin1Char('&')); // we assume that if name.isEmpty() then an + // accelerator is defined in description + } + + TikzCommand tikzCommand = + newCommand(name, description, insertion, highlightString, + commandObject.value(QLatin1String("dx")).toInt(), + commandObject.value(QLatin1String("dy")).toInt(), type); + tikzCommand.number = tikzCommandsList->size(); + tikzCommandsList->append(tikzCommand); + commands << tikzCommand; + } + } + } + } + commandList.commands = commands; + + return commandList; } -static TikzCommandList loadCommandsJson(const QString &fileName, QList *tikzCommandsList) +static TikzCommandList loadCommandsJson(const QString &fileName, + QList *tikzCommandsList) { - TikzCommandList commandList; - - QFile commandsFile(fileName); - if (!commandsFile.open(QIODevice::ReadOnly | QIODevice::Text)) - return commandList; - - QJsonParseError error; - QJsonDocument commandsDocument = QJsonDocument::fromJson(commandsFile.readAll(), &error); - if (error.error != QJsonParseError::NoError) - { - qCritical("Parse error in TikZ commands file %s at offset %d:\n%s", qPrintable(fileName), error.offset, qPrintable(error.errorString())); - return commandList; - } - if (commandsDocument.isObject()) - { - QJsonObject sectionObject = commandsDocument.object(); - commandList = loadChildCommandsJson(sectionObject, tikzCommandsList); - } - return commandList; + TikzCommandList commandList; + + QFile commandsFile(fileName); + if (!commandsFile.open(QIODevice::ReadOnly | QIODevice::Text)) + return commandList; + + QJsonParseError error; + QJsonDocument commandsDocument = QJsonDocument::fromJson(commandsFile.readAll(), &error); + if (error.error != QJsonParseError::NoError) { + qCritical("Parse error in TikZ commands file %s at offset %d:\n%s", qPrintable(fileName), + error.offset, qPrintable(error.errorString())); + return commandList; + } + if (commandsDocument.isObject()) { + QJsonObject sectionObject = commandsDocument.object(); + commandList = loadChildCommandsJson(sectionObject, tikzCommandsList); + } + return commandList; } void TikzCommandInserter::loadCommands() { - if (!m_tikzSections.commands.isEmpty()) - return; // don't load the commands again when opening a second window + if (!m_tikzSections.commands.isEmpty()) + return; // don't load the commands again when opening a second window - m_tikzSections = loadCommandsJson(QLatin1String(":/tikzcommands.json"), &m_tikzCommandsList); + m_tikzSections = loadCommandsJson(QLatin1String(":/tikzcommands.json"), &m_tikzCommandsList); } /***************************************************************************/ static QString removeOptionsAndSpecialCharacters(const QString &text) { - bool isInOption = false; - for (int i = 0; i < text.length(); ++i) - { - if (isInOption) - continue; - QChar::Category cat = text.at(i).category(); - if (cat == QChar::Letter_Lowercase || cat == QChar::Letter_Uppercase || text.at(i) == QLatin1Char('\\')) - return text.mid(i); - if (text.at(i) == QLatin1Char('<')) - { - isInOption = true; - continue; - } - else if (text.at(i) == QLatin1Char('>')) - { - isInOption = false; - continue; - } - } - return QString(); + bool isInOption = false; + for (int i = 0; i < text.length(); ++i) { + if (isInOption) + continue; + QChar::Category cat = text.at(i).category(); + if (cat == QChar::Letter_Lowercase || cat == QChar::Letter_Uppercase + || text.at(i) == QLatin1Char('\\')) + return text.mid(i); + if (text.at(i) == QLatin1Char('<')) { + isInOption = true; + continue; + } else if (text.at(i) == QLatin1Char('>')) { + isInOption = false; + continue; + } + } + return QString(); } QStringList TikzCommandInserter::getCommandWords() { - QStringList words; - -// QRegExp rx1(QLatin1String("^([^a-z\\\\<>]*<[^>]*>)*")); -// QRegExp rx2(QLatin1String("^[^a-z\\\\]*")); -// QString allowedLetters = QLatin1String("abcdefghijklmnopqrstuvwxyz\\"); - for (int i = 0; i < m_tikzCommandsList.size(); ++i) - { - QString word = m_tikzCommandsList.at(i).description; - // remove all special characters and at the beginning of the word -/* - if (!word.isEmpty() && !allowedLetters.contains(word.at(0))) // minimize the number of uses of QRegExp - { - word.remove(rx1); - word.remove(rx2); - } - if (!word.isEmpty()) - words.append(word); - else - { - word = m_tikzCommandsList.at(i).command; - // remove all special characters and at the beginning of the word - if (!word.isEmpty() && !allowedLetters.contains(word.at(0))) // minimize the number of uses of QRegExp - { - word.remove(rx1); - word.remove(rx2); - } - if (!word.isEmpty()) - words.append(word); - } -*/ - if (word.isEmpty()) - word = m_tikzCommandsList.at(i).command; - word = removeOptionsAndSpecialCharacters(word); - if (!word.isEmpty()) - words.append(word); - } - - return words; + QStringList words; + + // QRegExp rx1(QLatin1String("^([^a-z\\\\<>]*<[^>]*>)*")); + // QRegExp rx2(QLatin1String("^[^a-z\\\\]*")); + // QString allowedLetters = QLatin1String("abcdefghijklmnopqrstuvwxyz\\"); + for (int i = 0; i < m_tikzCommandsList.size(); ++i) { + QString word = m_tikzCommandsList.at(i).description; + // remove all special characters and at the beginning of the word + /* + if (!word.isEmpty() && !allowedLetters.contains(word.at(0))) // minimize the + number of uses of QRegExp + { + word.remove(rx1); + word.remove(rx2); + } + if (!word.isEmpty()) + words.append(word); + else + { + word = m_tikzCommandsList.at(i).command; + // remove all special characters and at the beginning of + the word if (!word.isEmpty() && !allowedLetters.contains(word.at(0))) // minimize the + number of uses of QRegExp + { + word.remove(rx1); + word.remove(rx2); + } + if (!word.isEmpty()) + words.append(word); + } + */ + if (word.isEmpty()) + word = m_tikzCommandsList.at(i).command; + word = removeOptionsAndSpecialCharacters(word); + if (!word.isEmpty()) + words.append(word); + } + + return words; } /*! @@ -350,53 +372,53 @@ QStringList TikzCommandInserter::getCommandWords() void TikzCommandInserter::updateDescriptionToolTip() { - QAction *action = qobject_cast(sender()); - if (action) - { - const int num = action->data().toInt(); - const TikzCommand cmd = m_tikzCommandsList.at(num); - QString description = cmd.description; - description.replace(QLatin1Char('&'), QLatin1String("&")); - description.replace(QLatin1Char('<'), QLatin1String("<")); - description.replace(QLatin1Char('>'), QLatin1String(">")); - QMenu *menu = qobject_cast(action->parentWidget()); - const QRect rect = menu->actionGeometry(action); - QToolTip::showText(menu->mapToGlobal(QPoint(rect.x() + rect.width(), rect.y() - rect.height() / 2)), QLatin1String("

") + description + QLatin1String("

"), menu, rect, 5000); - } + QAction *action = qobject_cast(sender()); + if (action) { + const int num = action->data().toInt(); + const TikzCommand cmd = m_tikzCommandsList.at(num); + QString description = cmd.description; + description.replace(QLatin1Char('&'), QLatin1String("&")); + description.replace(QLatin1Char('<'), QLatin1String("<")); + description.replace(QLatin1Char('>'), QLatin1String(">")); + QMenu *menu = qobject_cast(action->parentWidget()); + const QRect rect = menu->actionGeometry(action); + QToolTip::showText( + menu->mapToGlobal(QPoint(rect.x() + rect.width(), rect.y() - rect.height() / 2)), + QLatin1String("

") + description + QLatin1String("

"), menu, rect, 5000); + } } QMenu *TikzCommandInserter::getMenu(const TikzCommandList &commandList, QWidget *parent) { - QMenu *menu = new QMenu(commandList.title, parent); - const int numOfCommands = commandList.commands.size(); - int whichSection = 0; - - for (int i = 0; i < numOfCommands; ++i) - { - const QString name = commandList.commands.at(i).name; - if (name.isEmpty()) // add separator or submenu - { - if (commandList.commands.at(i).type == 0) - { - menu->addSeparator(); - } - else // type == -1, so add submenu; this assumes that the i-th command with type == -1 corresponds with the i-th submenu (see getCommands()) - { - menu->addMenu(getMenu(commandList.children.at(whichSection), parent)); - ++whichSection; - } - } - else // add command - { - QAction *action = menu->addAction(name); - action->setData(commandList.commands.at(i).number); // link to the corresponding item in m_tikzCommandsList - action->setStatusTip(commandList.commands.at(i).description); - connect(action, SIGNAL(triggered()), this, SLOT(insertTag())); - connect(action, SIGNAL(hovered()), this, SLOT(updateDescriptionToolTip())); - } - } - - return menu; + QMenu *menu = new QMenu(commandList.title, parent); + const int numOfCommands = commandList.commands.size(); + int whichSection = 0; + + for (int i = 0; i < numOfCommands; ++i) { + const QString name = commandList.commands.at(i).name; + if (name.isEmpty()) // add separator or submenu + { + if (commandList.commands.at(i).type == 0) { + menu->addSeparator(); + } else // type == -1, so add submenu; this assumes that the i-th command with type == -1 + // corresponds with the i-th submenu (see getCommands()) + { + menu->addMenu(getMenu(commandList.children.at(whichSection), parent)); + ++whichSection; + } + } else // add command + { + QAction *action = menu->addAction(name); + action->setData( + commandList.commands.at(i) + .number); // link to the corresponding item in m_tikzCommandsList + action->setStatusTip(commandList.commands.at(i).description); + connect(action, SIGNAL(triggered()), this, SLOT(insertTag())); + connect(action, SIGNAL(hovered()), this, SLOT(updateDescriptionToolTip())); + } + } + + return menu; } /*! @@ -407,7 +429,7 @@ QMenu *TikzCommandInserter::getMenu(const TikzCommandList &commandList, QWidget QMenu *TikzCommandInserter::getMenu() { - return getMenu(m_tikzSections, qobject_cast(parent())); + return getMenu(m_tikzSections, qobject_cast(parent())); } //@} @@ -417,74 +439,91 @@ QMenu *TikzCommandInserter::getMenu() */ //@{ -void TikzCommandInserter::addListWidgetItems(QListWidget *listWidget, const QPalette &standardPalette, const TikzCommandList &commandList, bool addChildren) +void TikzCommandInserter::addListWidgetItems(QListWidget *listWidget, + const QPalette &standardPalette, + const TikzCommandList &commandList, bool addChildren) { - QFont titleFont = qApp->font(); - titleFont.setBold(true); -// QColor titleBg(standardPalette.color(QPalette::Normal, QPalette::Highlight)); -// titleBg = titleBg.lighter(120); - QColor titleBg(standardPalette.color(QPalette::Normal, QPalette::Window)); - titleBg = titleBg.darker(200); - QColor titleFg(standardPalette.color(QPalette::Normal, QPalette::HighlightedText)); -// QColor separatorBg(standardPalette.color(QPalette::Normal, QPalette::AlternateBase)); -// if (separatorBg == standardPalette.color(QPalette::Normal, QPalette::Base)) -// separatorBg = separatorBg.darker(110); - - for (int i = 0; i < commandList.commands.size(); ++i) - { - if (commandList.commands.at(i).type == -1) // if we have an empty command corresponding to a submenu, then don't add the command, the submenus will be added later - continue; - QString itemText = commandList.commands.at(i).name; - if (itemText.isEmpty()) - continue; - - QListWidgetItem *item = new QListWidgetItem(listWidget); - item->setText(itemText.remove(QLatin1Char('&'))); - -// if (itemText.isEmpty()) -// item->setBackgroundColor(separatorBg); -// else - item->setData(Qt::UserRole, commandList.commands.at(i).number); // link to the corresponding item in m_tikzCommandsList - } - - if (!addChildren) return; - - for (int i = 0; i < commandList.children.size(); ++i) - { - QListWidgetItem *item = new QListWidgetItem(listWidget); - QString itemText = commandList.children.at(i).title; - item->setText(itemText.remove(QLatin1Char('&'))); - - item->setBackgroundColor(titleBg); - item->setTextColor(titleFg); - item->setFont(titleFont); - - addListWidgetItems(listWidget, standardPalette, commandList.children.at(i)); - } + QFont titleFont = qApp->font(); + titleFont.setBold(true); + // QColor titleBg(standardPalette.color(QPalette::Normal, QPalette::Highlight)); + // titleBg = titleBg.lighter(120); + QColor titleBg(standardPalette.color(QPalette::Normal, QPalette::Window)); + titleBg = titleBg.darker(200); + QColor titleFg(standardPalette.color(QPalette::Normal, QPalette::HighlightedText)); + // QColor separatorBg(standardPalette.color(QPalette::Normal, QPalette::AlternateBase)); + // if (separatorBg == standardPalette.color(QPalette::Normal, QPalette::Base)) + // separatorBg = separatorBg.darker(110); + + for (int i = 0; i < commandList.commands.size(); ++i) { + if (commandList.commands.at(i).type + == -1) // if we have an empty command corresponding to a submenu, then don't add the + // command, the submenus will be added later + continue; + QString itemText = commandList.commands.at(i).name; + if (itemText.isEmpty()) + continue; + + QListWidgetItem *item = new QListWidgetItem(listWidget); + item->setText(itemText.remove(QLatin1Char('&'))); + + // if (itemText.isEmpty()) + // item->setBackgroundColor(separatorBg); + // else + item->setData(Qt::UserRole, + commandList.commands.at(i) + .number); // link to the corresponding item in m_tikzCommandsList + } + + if (!addChildren) + return; + + for (int i = 0; i < commandList.children.size(); ++i) { + QListWidgetItem *item = new QListWidgetItem(listWidget); + QString itemText = commandList.children.at(i).title; + item->setText(itemText.remove(QLatin1Char('&'))); + + item->setBackgroundColor(titleBg); + item->setTextColor(titleFg); + item->setFont(titleFont); + + addListWidgetItems(listWidget, standardPalette, commandList.children.at(i)); + } } void TikzCommandInserter::showItemsInDockWidget() { - Q_ASSERT_X(m_commandsCombo, "TikzCommandInserter::showItemsInDockWidget()", "TikzCommandInserter::getDockWidget(QWidget *parent) should be run before using this function"); - Q_ASSERT_X(m_commandsStack, "TikzCommandInserter::showItemsInDockWidget()", "TikzCommandInserter::getDockWidget(QWidget *parent) should be run before using this function"); - QListWidget *tikzListWidget = qobject_cast(m_commandsStack->widget(0)); - QPalette standardPalette = QApplication::style()->standardPalette(); // this is slow, so we call this only once here and pass this as argument to addListWidgetItems instead of calling this each time in addListWidgetItems - addListWidgetItems(tikzListWidget, standardPalette, m_tikzSections, false); // don't add children - - for (int i = 0; i < m_tikzSections.children.size(); ++i) - { - QListWidget *tikzListWidget = new QListWidget; - addListWidgetItems(tikzListWidget, standardPalette, m_tikzSections.children.at(i)); - tikzListWidget->setMouseTracking(true); - connect(tikzListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(setListStatusTip(QListWidgetItem*))); - connect(tikzListWidget, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(setListStatusTip(QListWidgetItem*))); - connect(tikzListWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(insertTag(QListWidgetItem*))); -// connect(tikzListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(insertTag(QListWidgetItem*))); - - QString comboItemText = m_tikzSections.children.at(i).title; - m_commandsCombo->addItem(comboItemText.remove(QLatin1Char('&'))); - m_commandsStack->addWidget(tikzListWidget); - } + Q_ASSERT_X(m_commandsCombo, "TikzCommandInserter::showItemsInDockWidget()", + "TikzCommandInserter::getDockWidget(QWidget *parent) should be run before using " + "this function"); + Q_ASSERT_X(m_commandsStack, "TikzCommandInserter::showItemsInDockWidget()", + "TikzCommandInserter::getDockWidget(QWidget *parent) should be run before using " + "this function"); + QListWidget *tikzListWidget = qobject_cast(m_commandsStack->widget(0)); + QPalette standardPalette = + QApplication::style() + ->standardPalette(); // this is slow, so we call this only once here and pass + // this as argument to addListWidgetItems instead of + // calling this each time in addListWidgetItems + addListWidgetItems(tikzListWidget, standardPalette, m_tikzSections, + false); // don't add children + + for (int i = 0; i < m_tikzSections.children.size(); ++i) { + QListWidget *tikzListWidget = new QListWidget; + addListWidgetItems(tikzListWidget, standardPalette, m_tikzSections.children.at(i)); + tikzListWidget->setMouseTracking(true); + connect(tikzListWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), + this, SLOT(setListStatusTip(QListWidgetItem *))); + connect(tikzListWidget, SIGNAL(itemEntered(QListWidgetItem *)), this, + SLOT(setListStatusTip(QListWidgetItem *))); + connect(tikzListWidget, SIGNAL(itemActivated(QListWidgetItem *)), this, + SLOT(insertTag(QListWidgetItem *))); + // connect(tikzListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, + //SLOT(insertTag(QListWidgetItem*))); + + QString comboItemText = m_tikzSections.children.at(i).title; + m_commandsCombo->addItem(comboItemText.remove(QLatin1Char('&'))); + m_commandsStack->addWidget(tikzListWidget); + } } /*! @@ -496,59 +535,63 @@ void TikzCommandInserter::showItemsInDockWidget() QDockWidget *TikzCommandInserter::getDockWidget(QWidget *parent) { - QDockWidget *tikzDock = new QDockWidget(parent); - tikzDock->setObjectName(QLatin1String("CommandsDock")); - tikzDock->setAllowedAreas(Qt::AllDockWidgetAreas); - tikzDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); - tikzDock->setWindowTitle(m_tikzSections.title); - tikzDock->setWhatsThis(tr("

This is a list of TikZ " - "commands. You can insert these commands in your code by " - "clicking on them. You can obtain more commands by " - "changing the category in the combo box.

")); - - QAction *focusTikzDockAction = new QAction(parent); - focusTikzDockAction->setShortcut(QKeySequence(tr("Alt+I"))); - tikzDock->addAction(focusTikzDockAction); - connect(focusTikzDockAction, SIGNAL(triggered()), tikzDock, SLOT(setFocus())); - - QLabel *commandsComboLabel = new QLabel(tr("Category:")); - m_commandsCombo = new ComboBox; - m_commandsCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - m_commandsStack = new QStackedWidget; - connect(m_commandsCombo, SIGNAL(currentIndexChanged(int)), m_commandsStack, SLOT(setCurrentIndex(int))); - - QListWidget *tikzListWidget = new QListWidget; - tikzListWidget->setMouseTracking(true); - connect(tikzListWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(setListStatusTip(QListWidgetItem*))); - connect(tikzListWidget, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(setListStatusTip(QListWidgetItem*))); - connect(tikzListWidget, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(insertTag(QListWidgetItem*))); -// connect(tikzListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(insertTag(QListWidgetItem*))); - m_commandsCombo->addItem(tr("General")); - m_commandsStack->addWidget(tikzListWidget); - - QGridLayout *tikzLayout = new QGridLayout; - tikzLayout->addWidget(commandsComboLabel, 0, 0); - tikzLayout->addWidget(m_commandsCombo, 0, 1); - tikzLayout->addWidget(m_commandsStack, 1, 0, 1, 2); - tikzLayout->setMargin(5); - - TikzCommandWidget *tikzWidget = new TikzCommandWidget; - tikzWidget->setLayout(tikzLayout); - tikzDock->setWidget(tikzWidget); - tikzDock->setFocusProxy(m_commandsCombo); - - return tikzDock; + QDockWidget *tikzDock = new QDockWidget(parent); + tikzDock->setObjectName(QLatin1String("CommandsDock")); + tikzDock->setAllowedAreas(Qt::AllDockWidgetAreas); + tikzDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable + | QDockWidget::DockWidgetFloatable); + tikzDock->setWindowTitle(m_tikzSections.title); + tikzDock->setWhatsThis(tr("

This is a list of TikZ " + "commands. You can insert these commands in your code by " + "clicking on them. You can obtain more commands by " + "changing the category in the combo box.

")); + + QAction *focusTikzDockAction = new QAction(parent); + focusTikzDockAction->setShortcut(QKeySequence(tr("Alt+I"))); + tikzDock->addAction(focusTikzDockAction); + connect(focusTikzDockAction, SIGNAL(triggered()), tikzDock, SLOT(setFocus())); + + QLabel *commandsComboLabel = new QLabel(tr("Category:")); + m_commandsCombo = new ComboBox; + m_commandsCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + m_commandsStack = new QStackedWidget; + connect(m_commandsCombo, SIGNAL(currentIndexChanged(int)), m_commandsStack, + SLOT(setCurrentIndex(int))); + + QListWidget *tikzListWidget = new QListWidget; + tikzListWidget->setMouseTracking(true); + connect(tikzListWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, + SLOT(setListStatusTip(QListWidgetItem *))); + connect(tikzListWidget, SIGNAL(itemEntered(QListWidgetItem *)), this, + SLOT(setListStatusTip(QListWidgetItem *))); + connect(tikzListWidget, SIGNAL(itemActivated(QListWidgetItem *)), this, + SLOT(insertTag(QListWidgetItem *))); + // connect(tikzListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, + //SLOT(insertTag(QListWidgetItem*))); + m_commandsCombo->addItem(tr("General")); + m_commandsStack->addWidget(tikzListWidget); + + QGridLayout *tikzLayout = new QGridLayout; + tikzLayout->addWidget(commandsComboLabel, 0, 0); + tikzLayout->addWidget(m_commandsCombo, 0, 1); + tikzLayout->addWidget(m_commandsStack, 1, 0, 1, 2); + tikzLayout->setMargin(5); + + TikzCommandWidget *tikzWidget = new TikzCommandWidget; + tikzWidget->setLayout(tikzLayout); + tikzDock->setWidget(tikzWidget); + tikzDock->setFocusProxy(m_commandsCombo); + + return tikzDock; } void TikzCommandInserter::setListStatusTip(QListWidgetItem *item) { - if (item && !item->font().bold() && !item->text().isEmpty()) - { - const int num = item->data(Qt::UserRole).toInt(); - Q_EMIT showStatusMessage(m_tikzCommandsList.at(num).description, 10000); - } - else - Q_EMIT showStatusMessage(QString()); + if (item && !item->font().bold() && !item->text().isEmpty()) { + const int num = item->data(Qt::UserRole).toInt(); + Q_EMIT showStatusMessage(m_tikzCommandsList.at(num).description, 10000); + } else + Q_EMIT showStatusMessage(QString()); } //@} @@ -563,28 +606,28 @@ void TikzCommandInserter::setListStatusTip(QListWidgetItem *item) QMap TikzCommandInserter::getDefaultHighlightFormats() { - QMap formatList; - QStringList highlightTypeNames = getHighlightTypeNames(); - - QTextCharFormat commandFormat; - commandFormat.setForeground(QColor(QLatin1String("#004080"))); - commandFormat.setFont(qApp->font()); - commandFormat.setFontWeight(QFont::Bold); - formatList[highlightTypeNames.at(0)] = commandFormat; - - QTextCharFormat drawFormat; - drawFormat.setForeground(Qt::darkRed); - drawFormat.setFont(qApp->font()); - drawFormat.setFontWeight(QFont::Normal); - formatList[highlightTypeNames.at(1)] = drawFormat; - - QTextCharFormat optionFormat; - optionFormat.setForeground(QColor(QLatin1String("#004000"))); - optionFormat.setFont(qApp->font()); - optionFormat.setFontWeight(QFont::Normal); - formatList[highlightTypeNames.at(2)] = optionFormat; - - return formatList; + QMap formatList; + QStringList highlightTypeNames = getHighlightTypeNames(); + + QTextCharFormat commandFormat; + commandFormat.setForeground(QColor(QLatin1String("#004080"))); + commandFormat.setFont(qApp->font()); + commandFormat.setFontWeight(QFont::Bold); + formatList[highlightTypeNames.at(0)] = commandFormat; + + QTextCharFormat drawFormat; + drawFormat.setForeground(Qt::darkRed); + drawFormat.setFont(qApp->font()); + drawFormat.setFontWeight(QFont::Normal); + formatList[highlightTypeNames.at(1)] = drawFormat; + + QTextCharFormat optionFormat; + optionFormat.setForeground(QColor(QLatin1String("#004000"))); + optionFormat.setFont(qApp->font()); + optionFormat.setFontWeight(QFont::Normal); + formatList[highlightTypeNames.at(2)] = optionFormat; + + return formatList; } /*! @@ -598,9 +641,9 @@ QMap TikzCommandInserter::getDefaultHighlightFormats() QStringList TikzCommandInserter::getTranslatedHighlightTypeNames() { - QStringList translatedHighlightTypeNames; - translatedHighlightTypeNames << tr("Commands") << tr("Draw to") << tr("Options"); - return translatedHighlightTypeNames; + QStringList translatedHighlightTypeNames; + translatedHighlightTypeNames << tr("Commands") << tr("Draw to") << tr("Options"); + return translatedHighlightTypeNames; } /*! @@ -613,9 +656,10 @@ QStringList TikzCommandInserter::getTranslatedHighlightTypeNames() QStringList TikzCommandInserter::getHighlightTypeNames() { - QStringList highlightTypeNames; - highlightTypeNames << QLatin1String("Commands") << QLatin1String("Draw to") << QLatin1String("Options"); - return highlightTypeNames; + QStringList highlightTypeNames; + highlightTypeNames << QLatin1String("Commands") << QLatin1String("Draw to") + << QLatin1String("Options"); + return highlightTypeNames; } /*! @@ -627,109 +671,107 @@ QStringList TikzCommandInserter::getHighlightTypeNames() QVector TikzCommandInserter::getHighlightingRules() { - QVector highlightingRules; - HighlightingRule rule; - QStringList highlightTypeNames = getHighlightTypeNames(); - - for (int i = 0; i < m_tikzCommandsList.size(); ++i) - { - QString command = m_tikzCommandsList.at(i).command.isEmpty() ? m_tikzCommandsList.at(i).description : m_tikzCommandsList.at(i).command; - const int type = m_tikzCommandsList.at(i).type; - int end; - rule.isRegExp = false; - if (!m_tikzCommandsList.at(i).highlightString.isEmpty()) - { - rule.pattern = QRegExp(m_tikzCommandsList.at(i).highlightString); - rule.isRegExp = true; - } - switch (type) - { - case 1: - { - const int end1 = command.indexOf(QLatin1Char(' '), 0); - const int end2 = command.indexOf(QLatin1Char('['), 0); - const int end3 = command.indexOf(QLatin1Char('{'), 0); - end = end1; - if (end < 0 || (end2 >= 0 && end2 < end)) - end = end2; - if (end < 0 || (end3 >= 0 && end3 < end)) - end = end3; - - command = command.left(end); -// command = command.replace(QLatin1Char('\\'), QLatin1String("\\\\")); - rule.type = highlightTypeNames.at(0); -// rule.pattern = QRegExp(command); -// rule.pattern.setPattern(command); - rule.matchString = command; - highlightingRules.append(rule); - break; - } - case 2: -// command = command.replace("()", "\\([^\\)]*\\)"); -// command = command.replace("(,)", "\\([^\\)]*\\)"); -// command = command.replace("(:::)", "\\([^\\)]*\\)"); - command = command.remove(QLatin1Char('+')); - command = command.remove(QLatin1String(" ()")); - command = command.remove(QLatin1String(" (,)")); - command = command.remove(QLatin1String(" (:::)")); - command = command.remove(QLatin1String(" {} ")); - rule.type = highlightTypeNames.at(1); -// rule.pattern = QRegExp(command); -// rule.pattern.setPattern(command); - rule.matchString = command; - highlightingRules.append(rule); - break; - case 3: -// command = command.replace(QLatin1Char('|'), QLatin1String("\\|")); - end = command.indexOf(QLatin1Char('='), 0) + 1; - if (end > 0) - command = command.left(end); - rule.type = highlightTypeNames.at(2); -// rule.pattern = QRegExp(command); -// rule.pattern.setPattern(command); - rule.matchString = command; - highlightingRules.append(rule); - break; - } - } - - return highlightingRules; + QVector highlightingRules; + HighlightingRule rule; + QStringList highlightTypeNames = getHighlightTypeNames(); + + for (int i = 0; i < m_tikzCommandsList.size(); ++i) { + QString command = m_tikzCommandsList.at(i).command.isEmpty() + ? m_tikzCommandsList.at(i).description + : m_tikzCommandsList.at(i).command; + const int type = m_tikzCommandsList.at(i).type; + int end; + rule.isRegExp = false; + if (!m_tikzCommandsList.at(i).highlightString.isEmpty()) { + rule.pattern = QRegExp(m_tikzCommandsList.at(i).highlightString); + rule.isRegExp = true; + } + switch (type) { + case 1: { + const int end1 = command.indexOf(QLatin1Char(' '), 0); + const int end2 = command.indexOf(QLatin1Char('['), 0); + const int end3 = command.indexOf(QLatin1Char('{'), 0); + end = end1; + if (end < 0 || (end2 >= 0 && end2 < end)) + end = end2; + if (end < 0 || (end3 >= 0 && end3 < end)) + end = end3; + + command = command.left(end); + // command = command.replace(QLatin1Char('\\'), + //QLatin1String("\\\\")); + rule.type = highlightTypeNames.at(0); + // rule.pattern = QRegExp(command); + // rule.pattern.setPattern(command); + rule.matchString = command; + highlightingRules.append(rule); + break; + } + case 2: + // command = command.replace("()", "\\([^\\)]*\\)"); + // command = command.replace("(,)", "\\([^\\)]*\\)"); + // command = command.replace("(:::)", "\\([^\\)]*\\)"); + command = command.remove(QLatin1Char('+')); + command = command.remove(QLatin1String(" ()")); + command = command.remove(QLatin1String(" (,)")); + command = command.remove(QLatin1String(" (:::)")); + command = command.remove(QLatin1String(" {} ")); + rule.type = highlightTypeNames.at(1); + // rule.pattern = QRegExp(command); + // rule.pattern.setPattern(command); + rule.matchString = command; + highlightingRules.append(rule); + break; + case 3: + // command = command.replace(QLatin1Char('|'), + //QLatin1String("\\|")); + end = command.indexOf(QLatin1Char('='), 0) + 1; + if (end > 0) + command = command.left(end); + rule.type = highlightTypeNames.at(2); + // rule.pattern = QRegExp(command); + // rule.pattern.setPattern(command); + rule.matchString = command; + highlightingRules.append(rule); + break; + } + } + + return highlightingRules; } void TikzCommandInserter::insertTag() { - QAction *action = qobject_cast(sender()); - if (action) - { - const int num = action->data().toInt(); - const TikzCommand cmd = m_tikzCommandsList.at(num); - Q_EMIT showStatusMessage(cmd.description, 0); - const QString command = cmd.command.isEmpty() ? cmd.description : cmd.command; - insertTag(command, cmd.dx, cmd.dy); - } + QAction *action = qobject_cast(sender()); + if (action) { + const int num = action->data().toInt(); + const TikzCommand cmd = m_tikzCommandsList.at(num); + Q_EMIT showStatusMessage(cmd.description, 0); + const QString command = cmd.command.isEmpty() ? cmd.description : cmd.command; + insertTag(command, cmd.dx, cmd.dy); + } } void TikzCommandInserter::insertTag(QListWidgetItem *item) { - if (item && !item->font().bold() && !item->text().isEmpty()) - { - const int num = item->data(Qt::UserRole).toInt(); - const TikzCommand cmd = m_tikzCommandsList.at(num); - Q_EMIT showStatusMessage(cmd.description, 0); - const QString command = cmd.command.isEmpty() ? cmd.description : cmd.command; - insertTag(command, cmd.dx, cmd.dy); - } + if (item && !item->font().bold() && !item->text().isEmpty()) { + const int num = item->data(Qt::UserRole).toInt(); + const TikzCommand cmd = m_tikzCommandsList.at(num); + Q_EMIT showStatusMessage(cmd.description, 0); + const QString command = cmd.command.isEmpty() ? cmd.description : cmd.command; + insertTag(command, cmd.dx, cmd.dy); + } } #ifdef KTIKZ_USE_KTEXTEDITOR void TikzCommandInserter::setEditor(KTextEditor::Document *doc) { - m_mainKFEdit = doc; + m_mainKFEdit = doc; } #endif void TikzCommandInserter::setEditor(QPlainTextEdit *textEdit) { - m_mainEdit = textEdit; + m_mainEdit = textEdit; } /*! @@ -744,50 +786,49 @@ void TikzCommandInserter::setEditor(QPlainTextEdit *textEdit) void TikzCommandInserter::insertTag(const QString &tag, int dx, int dy) { #ifdef KTIKZ_USE_KTEXTEDITOR - if( m_mainKFEdit ) - { - Q_ASSERT_X(m_mainKFEdit, "TikzCommandInserter::insertTag(const QString &tag, int dx, int dy)", "m_mainEdit should be set using TikzCommandInserter::setEditor() before using this function"); - KTextEditor::View *documentView = m_mainKFEdit->views().at(0); - KTextEditor::Cursor cur = documentView->cursorPosition(); - m_mainKFEdit->insertText(cur, tag, true); - } - else - { + if (m_mainKFEdit) { + Q_ASSERT_X(m_mainKFEdit, + "TikzCommandInserter::insertTag(const QString &tag, int dx, int dy)", + "m_mainEdit should be set using TikzCommandInserter::setEditor() before using " + "this function"); + KTextEditor::View *documentView = m_mainKFEdit->views().at(0); + KTextEditor::Cursor cur = documentView->cursorPosition(); + m_mainKFEdit->insertText(cur, tag, true); + } else { #endif - Q_ASSERT_X(m_mainEdit, "TikzCommandInserter::insertTag(const QString &tag, int dx, int dy)", "m_mainEdit should be set using TikzCommandInserter::setEditor() before using this function"); - - // replace all options (between <...>) by a place holder - QString insertWord = tag; - const QRegExp rx(QLatin1String("<[^<>]*>")); - insertWord.replace(rx, s_completionPlaceHolder); - - QTextCursor cur = m_mainEdit->textCursor(); - const int pos = cur.position(); - - // insert tag - m_mainEdit->insertPlainText(insertWord); - cur.setPosition(pos, QTextCursor::MoveAnchor); - - // move the text cursor to the first option or to the specified place - if (insertWord.contains(s_completionPlaceHolder)) - { - cur = m_mainEdit->document()->find(s_completionPlaceHolder, cur); - m_mainEdit->setTextCursor(cur); - } - else if (dx > 0 || dy > 0) - { - if (dy > 0) - { - cur.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, dy); - cur.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor, 1); - } - if (dx > 0) - cur.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, dx); - m_mainEdit->setTextCursor(cur); - } - // else we are only inserting a string with no placeholders and no positioning, so the cursor must come at the end of the string (this is done automatically by Qt) - m_mainEdit->setFocus(); + Q_ASSERT_X(m_mainEdit, "TikzCommandInserter::insertTag(const QString &tag, int dx, int dy)", + "m_mainEdit should be set using TikzCommandInserter::setEditor() before using " + "this function"); + + // replace all options (between <...>) by a place holder + QString insertWord = tag; + const QRegExp rx(QLatin1String("<[^<>]*>")); + insertWord.replace(rx, s_completionPlaceHolder); + + QTextCursor cur = m_mainEdit->textCursor(); + const int pos = cur.position(); + + // insert tag + m_mainEdit->insertPlainText(insertWord); + cur.setPosition(pos, QTextCursor::MoveAnchor); + + // move the text cursor to the first option or to the specified place + if (insertWord.contains(s_completionPlaceHolder)) { + cur = m_mainEdit->document()->find(s_completionPlaceHolder, cur); + m_mainEdit->setTextCursor(cur); + } else if (dx > 0 || dy > 0) { + if (dy > 0) { + cur.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, dy); + cur.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor, 1); + } + if (dx > 0) + cur.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, dx); + m_mainEdit->setTextCursor(cur); + } + // else we are only inserting a string with no placeholders and no positioning, so the + // cursor must come at the end of the string (this is done automatically by Qt) + m_mainEdit->setFocus(); #ifdef KTIKZ_USE_KTEXTEDITOR - } + } #endif } diff --git a/app/tikzcommandinserter.h b/app/tikzcommandinserter.h index b4e7499..97c8c89 100644 --- a/app/tikzcommandinserter.h +++ b/app/tikzcommandinserter.h @@ -34,84 +34,83 @@ class ComboBox; class HighlightingRule; namespace KTextEditor { - class Document; +class Document; } struct TikzCommand { - QString name; - QString description; - QString command; - QString highlightString; - int dx; - int dy; - int type; - int number; + QString name; + QString description; + QString command; + QString highlightString; + int dx; + int dy; + int type; + int number; }; struct TikzCommandList { - QString title; - QList commands; - QList children; + QString title; + QList commands; + QList children; }; class TikzCommandInserter : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit TikzCommandInserter(QWidget *parent = 0); - - static void loadCommands(); - static QStringList getCommandWords(); - QMenu *getMenu(); - void showItemsInDockWidget(); - QDockWidget *getDockWidget(QWidget *parent = 0); - static QMap getDefaultHighlightFormats(); - static QStringList getTranslatedHighlightTypeNames(); - static QStringList getHighlightTypeNames(); - static QVector getHighlightingRules(); + explicit TikzCommandInserter(QWidget *parent = 0); + + static void loadCommands(); + static QStringList getCommandWords(); + QMenu *getMenu(); + void showItemsInDockWidget(); + QDockWidget *getDockWidget(QWidget *parent = 0); + static QMap getDefaultHighlightFormats(); + static QStringList getTranslatedHighlightTypeNames(); + static QStringList getHighlightTypeNames(); + static QVector getHighlightingRules(); #ifdef KTIKZ_USE_KTEXTEDITOR - void setEditor(KTextEditor::Document *textEdit); + void setEditor(KTextEditor::Document *textEdit); #endif - void setEditor(QPlainTextEdit *textEdit); - - + void setEditor(QPlainTextEdit *textEdit); public Q_SLOTS: - void insertTag(const QString &tag, int dx = 0, int dy = 0); + void insertTag(const QString &tag, int dx = 0, int dy = 0); Q_SIGNALS: - /*! - * This signal is emitted whenever a message should be shown in - * the statusbar. - * \param message the message to be shown in the status bar - * \param timeout the duration in milli-seconds (if non-zero) during which the message must be shown - */ - void showStatusMessage(const QString &message, int timeout = 0); + /*! + * This signal is emitted whenever a message should be shown in + * the statusbar. + * \param message the message to be shown in the status bar + * \param timeout the duration in milli-seconds (if non-zero) during which the message must be + * shown + */ + void showStatusMessage(const QString &message, int timeout = 0); private Q_SLOTS: - void updateDescriptionToolTip(); - void setListStatusTip(QListWidgetItem *item); - void insertTag(); - void insertTag(QListWidgetItem *item); + void updateDescriptionToolTip(); + void setListStatusTip(QListWidgetItem *item); + void insertTag(); + void insertTag(QListWidgetItem *item); private: - QMenu *getMenu(const TikzCommandList &commandList, QWidget *parent); - void addListWidgetItems(QListWidget *listWidget, const QPalette &standardPalette, const TikzCommandList &commandList, bool addChildren = true); + QMenu *getMenu(const TikzCommandList &commandList, QWidget *parent); + void addListWidgetItems(QListWidget *listWidget, const QPalette &standardPalette, + const TikzCommandList &commandList, bool addChildren = true); #ifdef KTIKZ_USE_KTEXTEDITOR - KTextEditor::Document *m_mainKFEdit; + KTextEditor::Document *m_mainKFEdit; #endif - QPlainTextEdit *m_mainEdit; - + QPlainTextEdit *m_mainEdit; - static TikzCommandList m_tikzSections; - static QList m_tikzCommandsList; + static TikzCommandList m_tikzSections; + static QList m_tikzCommandsList; - ComboBox *m_commandsCombo; - QStackedWidget *m_commandsStack; + ComboBox *m_commandsCombo; + QStackedWidget *m_commandsStack; }; #endif diff --git a/app/tikzcommandwidget.cpp b/app/tikzcommandwidget.cpp index dd483fa..2528d50 100644 --- a/app/tikzcommandwidget.cpp +++ b/app/tikzcommandwidget.cpp @@ -18,11 +18,9 @@ #include "tikzcommandwidget.h" -TikzCommandWidget::TikzCommandWidget(QWidget *parent) : QWidget(parent) -{ -} +TikzCommandWidget::TikzCommandWidget(QWidget *parent) : QWidget(parent) { } QSize TikzCommandWidget::sizeHint() const { - return QSize(100, 200); + return QSize(100, 200); } diff --git a/app/tikzcommandwidget.h b/app/tikzcommandwidget.h index bba51ba..5f594c0 100644 --- a/app/tikzcommandwidget.h +++ b/app/tikzcommandwidget.h @@ -24,11 +24,11 @@ class TikzCommandWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit TikzCommandWidget(QWidget *parent = 0); - virtual QSize sizeHint() const; + explicit TikzCommandWidget(QWidget *parent = 0); + virtual QSize sizeHint() const; }; #endif diff --git a/app/tikzdocumentationcontroller.cpp b/app/tikzdocumentationcontroller.cpp index c9030ff..44b9199 100644 --- a/app/tikzdocumentationcontroller.cpp +++ b/app/tikzdocumentationcontroller.cpp @@ -23,45 +23,47 @@ QString TikzDocumentationController::tikzDocumentationPath() { - QSettings settings; - QString tikzDocFile = settings.value(QLatin1String("TikzDocumentation")).toString(); - const bool tikzDocFileInSettingsEmpty = tikzDocFile.isEmpty(); + QSettings settings; + QString tikzDocFile = settings.value(QLatin1String("TikzDocumentation")).toString(); + const bool tikzDocFileInSettingsEmpty = tikzDocFile.isEmpty(); - if (tikzDocFileInSettingsEmpty) - tikzDocFile = searchTikzDocumentationInTexTree(); + if (tikzDocFileInSettingsEmpty) + tikzDocFile = searchTikzDocumentationInTexTree(); #ifdef KTIKZ_TIKZ_DOCUMENTATION_DEFAULT - if (tikzDocFile.isEmpty()) - tikzDocFile = QString::fromLocal8Bit(KTIKZ_TIKZ_DOCUMENTATION_DEFAULT); + if (tikzDocFile.isEmpty()) + tikzDocFile = QString::fromLocal8Bit(KTIKZ_TIKZ_DOCUMENTATION_DEFAULT); #endif - if (tikzDocFileInSettingsEmpty && !tikzDocFile.isEmpty()) - storeTikzDocumentationPath(tikzDocFile); + if (tikzDocFileInSettingsEmpty && !tikzDocFile.isEmpty()) + storeTikzDocumentationPath(tikzDocFile); - return tikzDocFile; + return tikzDocFile; } void TikzDocumentationController::storeTikzDocumentationPath(const QString &path) { - QSettings settings; - settings.setValue(QLatin1String("TikzDocumentation"), path); + QSettings settings; + settings.setValue(QLatin1String("TikzDocumentation"), path); } QString TikzDocumentationController::searchTikzDocumentationInTexTree() { - const QString kpsewhichCommand = QLatin1String("kpsewhich"); - QStringList kpsewhichArguments; - kpsewhichArguments << QLatin1String("--format") << QLatin1String("TeX system documentation") << QLatin1String("pgfmanual.pdf") << QLatin1String("pgfmanual.pdf.gz") << QLatin1String("pgfmanual.ps") << QLatin1String("pgfmanual.ps.gz"); + const QString kpsewhichCommand = QLatin1String("kpsewhich"); + QStringList kpsewhichArguments; + kpsewhichArguments << QLatin1String("--format") << QLatin1String("TeX system documentation") + << QLatin1String("pgfmanual.pdf") << QLatin1String("pgfmanual.pdf.gz") + << QLatin1String("pgfmanual.ps") << QLatin1String("pgfmanual.ps.gz"); - QProcess process; - process.start(kpsewhichCommand, kpsewhichArguments); - process.waitForStarted(1000); - while (process.state() != QProcess::NotRunning) - process.waitForFinished(100 /*msec*/); + QProcess process; + process.start(kpsewhichCommand, kpsewhichArguments); + process.waitForStarted(1000); + while (process.state() != QProcess::NotRunning) + process.waitForFinished(100 /*msec*/); - QString tikzDocFile = QString::fromLocal8Bit(process.readAllStandardOutput().constData()); - int newLinePosition = tikzDocFile.indexOf(QLatin1Char('\n')); - if (newLinePosition >= 0) - tikzDocFile.remove(newLinePosition, tikzDocFile.length()); - return tikzDocFile.trimmed(); + QString tikzDocFile = QString::fromLocal8Bit(process.readAllStandardOutput().constData()); + int newLinePosition = tikzDocFile.indexOf(QLatin1Char('\n')); + if (newLinePosition >= 0) + tikzDocFile.remove(newLinePosition, tikzDocFile.length()); + return tikzDocFile.trimmed(); } diff --git a/app/tikzdocumentationcontroller.h b/app/tikzdocumentationcontroller.h index 17ae28f..f6950d2 100644 --- a/app/tikzdocumentationcontroller.h +++ b/app/tikzdocumentationcontroller.h @@ -23,12 +23,12 @@ class TikzDocumentationController : public QObject { - Q_OBJECT + Q_OBJECT public: - static QString tikzDocumentationPath(); - static void storeTikzDocumentationPath(const QString &path); - static QString searchTikzDocumentationInTexTree(); + static QString tikzDocumentationPath(); + static void storeTikzDocumentationPath(const QString &path); + static QString searchTikzDocumentationInTexTree(); }; #endif diff --git a/app/tikzeditor.cpp b/app/tikzeditor.cpp index fa3449c..4c50865 100644 --- a/app/tikzeditor.cpp +++ b/app/tikzeditor.cpp @@ -53,71 +53,76 @@ static const QString s_completionPlaceHolder(0x2022); TikzEditor::TikzEditor(QWidget *parent) - : QPlainTextEdit(parent) - , m_highlightCurrentLineColor(Qt::yellow) - , m_highlightCurrentLine(true) - , m_oldVerticalScrollBarValue(0) - , m_whiteSpacesColor(Qt::gray) - , m_tabulatorsColor(Qt::gray) - , m_matchingColor(Qt::darkGreen) - , m_showWhiteSpaces(true) - , m_showTabulators(true) - , m_showMatchingBrackets(true) - , m_completer(0) - , m_oldNumOfLines(0) - , m_showLineNumberArea(true) + : QPlainTextEdit(parent), + m_highlightCurrentLineColor(Qt::yellow), + m_highlightCurrentLine(true), + m_oldVerticalScrollBarValue(0), + m_whiteSpacesColor(Qt::gray), + m_tabulatorsColor(Qt::gray), + m_matchingColor(Qt::darkGreen), + m_showWhiteSpaces(true), + m_showTabulators(true), + m_showMatchingBrackets(true), + m_completer(0), + m_oldNumOfLines(0), + m_showLineNumberArea(true) { - m_lineNumberArea = new LineNumberWidget(this); - updateLineNumberAreaWidth(); + m_lineNumberArea = new LineNumberWidget(this); + updateLineNumberAreaWidth(); - connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); - highlightCurrentLine(); + connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); + highlightCurrentLine(); - connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(showCursorPosition())); - connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(matchBrackets())); - connect(document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(recalculateBookmarks(int))); + connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(showCursorPosition())); + connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(matchBrackets())); + connect(document(), SIGNAL(contentsChange(int, int, int)), this, + SLOT(recalculateBookmarks(int))); - connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth())); - connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); + connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth())); + connect(this, SIGNAL(updateRequest(QRect, int)), this, SLOT(updateLineNumberArea(QRect, int))); } -TikzEditor::~TikzEditor() -{ -} +TikzEditor::~TikzEditor() { } void TikzEditor::highlightCurrentLine() { -/* - // this hides the white space and tab marks on the current line :-( - QList extraSelections; - if (!isReadOnly()) - { - QTextEdit::ExtraSelection selection; - selection.format.setBackground(m_highlightCurrentLineColor); - selection.format.setProperty(QTextFormat::FullWidthSelection, true); - selection.cursor = textCursor(); - selection.cursor.clearSelection(); - extraSelections.append(selection); - } - setExtraSelections(extraSelections); - - // highlight the currently selected brackets (if any) - matchBrackets(); -*/ - - // update the area covering the previously highlighted line (updating the whole viewport is too slow :-( ) - m_previousHighlightedLine.moveTop(m_previousHighlightedLine.top() - (verticalScrollBar()->value() - m_oldVerticalScrollBarValue + 0.5) * m_previousHighlightedLine.height()); - m_previousHighlightedLine.setHeight(2 * m_previousHighlightedLine.height()); // should be large enough to cover the previous line (ugly hack :-( ) - viewport()->update(m_previousHighlightedLine); - - // update the area covering the currently highlighted line - QRect rect = cursorRect(); - rect.setX(0); - rect.setWidth(viewport()->width()); - viewport()->update(rect); - - m_previousHighlightedLine = rect; - m_oldVerticalScrollBarValue = verticalScrollBar()->value(); + /* + // this hides the white space and tab marks on the current line :-( + QList extraSelections; + if (!isReadOnly()) + { + QTextEdit::ExtraSelection selection; + selection.format.setBackground(m_highlightCurrentLineColor); + selection.format.setProperty(QTextFormat::FullWidthSelection, true); + selection.cursor = textCursor(); + selection.cursor.clearSelection(); + extraSelections.append(selection); + } + setExtraSelections(extraSelections); + + // highlight the currently selected brackets (if any) + matchBrackets(); + */ + + // update the area covering the previously highlighted line (updating the whole viewport is too + // slow :-( ) + m_previousHighlightedLine.moveTop( + m_previousHighlightedLine.top() + - (verticalScrollBar()->value() - m_oldVerticalScrollBarValue + 0.5) + * m_previousHighlightedLine.height()); + m_previousHighlightedLine.setHeight( + 2 * m_previousHighlightedLine.height()); // should be large enough to cover the previous + // line (ugly hack :-( ) + viewport()->update(m_previousHighlightedLine); + + // update the area covering the currently highlighted line + QRect rect = cursorRect(); + rect.setX(0); + rect.setWidth(viewport()->width()); + viewport()->update(rect); + + m_previousHighlightedLine = rect; + m_oldVerticalScrollBarValue = verticalScrollBar()->value(); } /***************************************************************************/ @@ -126,282 +131,284 @@ namespace { bool isBracket(const QChar &c) { - return c == QLatin1Char('(') || c == QLatin1Char('{') || c == QLatin1Char('[') - || c == QLatin1Char(')') || c == QLatin1Char('}') || c == QLatin1Char(']'); + return c == QLatin1Char('(') || c == QLatin1Char('{') || c == QLatin1Char('[') + || c == QLatin1Char(')') || c == QLatin1Char('}') || c == QLatin1Char(']'); } } // anonymous namespace void TikzEditor::matchBrackets() { - // clear previous bracket highlighting - if (!isReadOnly()) - { - QList extraSelections; - QTextEdit::ExtraSelection selection; - selection.cursor = textCursor(); - selection.cursor.clearSelection(); - extraSelections.append(selection); - setExtraSelections(extraSelections); - } - - if (!m_showMatchingBrackets) - return; - - // find current matching brackets - const QTextCursor cursor = textCursor(); - const QTextDocument *document = this->document(); - int pos = cursor.position(); - if (!isBracket(document->characterAt(pos)) && (pos <= 0 || !isBracket(document->characterAt(--pos)))) // we do --pos because we want to match the bracket at both sides of the cursor - return; - - // get corresponding opening/closing bracket and search direction - const QChar car = document->characterAt(pos); - QChar matchCar; - int inc = 1; - if (car == QLatin1Char('(')) matchCar = QLatin1Char(')'); - else if (car == QLatin1Char('{')) matchCar = QLatin1Char('}'); - else if (car == QLatin1Char('[')) matchCar = QLatin1Char(']'); - else - { - inc = -1; - if (car == QLatin1Char(')')) matchCar = QLatin1Char('('); - else if (car == QLatin1Char('}')) matchCar = QLatin1Char('{'); - else if (car == QLatin1Char(']')) matchCar = QLatin1Char('['); - else - return; - } - - // find location of the corresponding bracket - int matchingBegin = pos; - int matchingEnd = -1; - int numOfMatchCharsToSkip = 0; - for (; pos >= 0 && pos < document->characterCount(); pos += inc) - { - if (document->characterAt(pos) == car) // if the brackets are nested, then don't match the closing bracket of the nested open bracket, e.g. in (()), don't match the first ) with the first ( - numOfMatchCharsToSkip++; - else if (document->characterAt(pos) == matchCar) - { - numOfMatchCharsToSkip--; - if (numOfMatchCharsToSkip == 0) - { - matchingEnd = pos; - break; - } - } - } - - if (matchingBegin > matchingEnd) - qSwap(matchingBegin, matchingEnd); - - // if there is a match, then show it - if (matchingBegin != -1) - showMatchingBrackets(matchingBegin, matchingEnd); + // clear previous bracket highlighting + if (!isReadOnly()) { + QList extraSelections; + QTextEdit::ExtraSelection selection; + selection.cursor = textCursor(); + selection.cursor.clearSelection(); + extraSelections.append(selection); + setExtraSelections(extraSelections); + } + + if (!m_showMatchingBrackets) + return; + + // find current matching brackets + const QTextCursor cursor = textCursor(); + const QTextDocument *document = this->document(); + int pos = cursor.position(); + if (!isBracket(document->characterAt(pos)) + && (pos <= 0 + || !isBracket(document->characterAt(--pos)))) // we do --pos because we want to match + // the bracket at both sides of the cursor + return; + + // get corresponding opening/closing bracket and search direction + const QChar car = document->characterAt(pos); + QChar matchCar; + int inc = 1; + if (car == QLatin1Char('(')) + matchCar = QLatin1Char(')'); + else if (car == QLatin1Char('{')) + matchCar = QLatin1Char('}'); + else if (car == QLatin1Char('[')) + matchCar = QLatin1Char(']'); + else { + inc = -1; + if (car == QLatin1Char(')')) + matchCar = QLatin1Char('('); + else if (car == QLatin1Char('}')) + matchCar = QLatin1Char('{'); + else if (car == QLatin1Char(']')) + matchCar = QLatin1Char('['); + else + return; + } + + // find location of the corresponding bracket + int matchingBegin = pos; + int matchingEnd = -1; + int numOfMatchCharsToSkip = 0; + for (; pos >= 0 && pos < document->characterCount(); pos += inc) { + if (document->characterAt(pos) + == car) // if the brackets are nested, then don't match the closing bracket of the + // nested open bracket, e.g. in (()), don't match the first ) with the first ( + numOfMatchCharsToSkip++; + else if (document->characterAt(pos) == matchCar) { + numOfMatchCharsToSkip--; + if (numOfMatchCharsToSkip == 0) { + matchingEnd = pos; + break; + } + } + } + + if (matchingBegin > matchingEnd) + qSwap(matchingBegin, matchingEnd); + + // if there is a match, then show it + if (matchingBegin != -1) + showMatchingBrackets(matchingBegin, matchingEnd); } void TikzEditor::showMatchingBrackets(int matchingBegin, int matchingEnd) { - if (isReadOnly()) - return; - - for (QTextBlock block = firstVisibleBlock(); block.isValid(); block = block.next()) - { - if (blockBoundingGeometry(block).top() > viewport()->height()) - break; - - const int textLength = block.text().length(); - const int blockPosition = block.position(); - for (int i = 0; i < textLength; ++i) - { - if (blockPosition + i == matchingBegin || blockPosition + i == matchingEnd) - { - QList extraSelectionList = extraSelections(); - QTextEdit::ExtraSelection selection; - selection.format.setBackground(m_matchingColor); - selection.cursor = textCursor(); - selection.cursor.setPosition(blockPosition + i, QTextCursor::MoveAnchor); - selection.cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); - extraSelectionList.append(selection); - setExtraSelections(extraSelectionList); - } - } - } + if (isReadOnly()) + return; + + for (QTextBlock block = firstVisibleBlock(); block.isValid(); block = block.next()) { + if (blockBoundingGeometry(block).top() > viewport()->height()) + break; + + const int textLength = block.text().length(); + const int blockPosition = block.position(); + for (int i = 0; i < textLength; ++i) { + if (blockPosition + i == matchingBegin || blockPosition + i == matchingEnd) { + QList extraSelectionList = extraSelections(); + QTextEdit::ExtraSelection selection; + selection.format.setBackground(m_matchingColor); + selection.cursor = textCursor(); + selection.cursor.setPosition(blockPosition + i, QTextCursor::MoveAnchor); + selection.cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); + extraSelectionList.append(selection); + setExtraSelections(extraSelectionList); + } + } + } } /***************************************************************************/ void TikzEditor::setShowWhiteSpaces(bool visible) { - m_showWhiteSpaces = visible; + m_showWhiteSpaces = visible; } void TikzEditor::setShowTabulators(bool visible) { - m_showTabulators = visible; + m_showTabulators = visible; } void TikzEditor::setShowMatchingBrackets(bool visible) { - m_showMatchingBrackets = visible; + m_showMatchingBrackets = visible; } void TikzEditor::setHighlightCurrentLine(bool visible) { - m_highlightCurrentLine = visible; + m_highlightCurrentLine = visible; } void TikzEditor::setWhiteSpacesColor(const QColor &color) { - m_whiteSpacesColor = color; + m_whiteSpacesColor = color; } void TikzEditor::setTabulatorsColor(const QColor &color) { - m_tabulatorsColor = color; + m_tabulatorsColor = color; } void TikzEditor::setMatchingColor(const QColor &color) { - m_matchingColor = color; + m_matchingColor = color; } void TikzEditor::setHighlightCurrentLineColor(const QColor &color) { - m_highlightCurrentLineColor = color; + m_highlightCurrentLineColor = color; } void TikzEditor::paintTabstop(QPainter &painter, qreal x, qreal y, int spaceWidth) { - qreal dist = spaceWidth * 0.3; -/* - QPointF points[8]; - points[0] = QPointF(x - dist, y - dist); - points[1] = QPointF(x, y); - points[2] = QPointF(x, y); - points[3] = QPointF(x - dist, y + dist); - x += spaceWidth / 3.0; - points[4] = QPointF(x - dist, y - dist); - points[5] = QPointF(x, y); - points[6] = QPointF(x, y); - points[7] = QPointF(x - dist, y + dist); - painter.drawLines(points, 4); -*/ - QPainterPath tabStopPath; - tabStopPath.moveTo(x - dist, y - dist); - tabStopPath.lineTo(x, y); - tabStopPath.lineTo(x - dist, y + dist); - x += spaceWidth / 3.0; - tabStopPath.moveTo(x - dist, y - dist); - tabStopPath.lineTo(x, y); - tabStopPath.lineTo(x - dist, y + dist); - painter.drawPath(tabStopPath); + qreal dist = spaceWidth * 0.3; + /* + QPointF points[8]; + points[0] = QPointF(x - dist, y - dist); + points[1] = QPointF(x, y); + points[2] = QPointF(x, y); + points[3] = QPointF(x - dist, y + dist); + x += spaceWidth / 3.0; + points[4] = QPointF(x - dist, y - dist); + points[5] = QPointF(x, y); + points[6] = QPointF(x, y); + points[7] = QPointF(x - dist, y + dist); + painter.drawLines(points, 4); + */ + QPainterPath tabStopPath; + tabStopPath.moveTo(x - dist, y - dist); + tabStopPath.lineTo(x, y); + tabStopPath.lineTo(x - dist, y + dist); + x += spaceWidth / 3.0; + tabStopPath.moveTo(x - dist, y - dist); + tabStopPath.lineTo(x, y); + tabStopPath.lineTo(x - dist, y + dist); + painter.drawPath(tabStopPath); } void TikzEditor::paintSpace(QPainter &painter, qreal x, qreal y, int spaceWidth) { - Q_UNUSED(spaceWidth); - painter.drawPoint(QPointF(x, y)); + Q_UNUSED(spaceWidth); + painter.drawPoint(QPointF(x, y)); } void TikzEditor::printWhiteSpaces(QPainter &painter) { - const QFontMetrics fontMetrics = QFontMetrics(document()->defaultFont()); - const int spaceWidth = fontMetrics.width(QLatin1Char(' ')); - const int fontHeight = fontMetrics.height(); - QTextCursor cursor = textCursor(); - - QPen backupPen(painter.pen()); - QPen tabulatorsPen(m_tabulatorsColor); - tabulatorsPen.setWidthF(qMax(qreal(0.5), qreal(spaceWidth * .1))); - tabulatorsPen.setCapStyle(Qt::RoundCap); - tabulatorsPen.setJoinStyle(Qt::RoundJoin); - QPen whiteSpacesPen(m_whiteSpacesColor); - whiteSpacesPen.setWidthF(spaceWidth / 3.5); - whiteSpacesPen.setCapStyle(Qt::RoundCap); - - for (QTextBlock block = firstVisibleBlock(); block.isValid(); block = block.next()) - { - if (blockBoundingGeometry(block).top() > viewport()->height()) // only paint white spaces in the visible part of the text - break; - - const QString text = block.text(); - const int textLength = text.length(); - const int blockPosition = block.position(); - for (int i = 0; i < textLength; ++i) - { - cursor.setPosition(blockPosition + i, QTextCursor::MoveAnchor); - const QRect rect = cursorRect(cursor); - -// const QFontMetrics fontMetrics = QFontMetrics(cursor.charFormat().font()); - - if (m_showWhiteSpaces && text.at(i) == QLatin1Char(' ')) - { - if (painter.pen() != whiteSpacesPen) - painter.setPen(whiteSpacesPen); - paintSpace(painter, rect.x() + spaceWidth / 2.0, rect.y() + fontHeight / 2.0, spaceWidth); - } - else if (m_showTabulators && text.at(i) == QLatin1Char('\t')) - { - if (painter.pen() != tabulatorsPen) - painter.setPen(tabulatorsPen); - paintTabstop(painter, rect.x() + spaceWidth / 2.0, rect.y() + fontHeight / 2.0, spaceWidth); - } - } - } - painter.setPen(backupPen); + const QFontMetrics fontMetrics = QFontMetrics(document()->defaultFont()); + const int spaceWidth = fontMetrics.width(QLatin1Char(' ')); + const int fontHeight = fontMetrics.height(); + QTextCursor cursor = textCursor(); + + QPen backupPen(painter.pen()); + QPen tabulatorsPen(m_tabulatorsColor); + tabulatorsPen.setWidthF(qMax(qreal(0.5), qreal(spaceWidth * .1))); + tabulatorsPen.setCapStyle(Qt::RoundCap); + tabulatorsPen.setJoinStyle(Qt::RoundJoin); + QPen whiteSpacesPen(m_whiteSpacesColor); + whiteSpacesPen.setWidthF(spaceWidth / 3.5); + whiteSpacesPen.setCapStyle(Qt::RoundCap); + + for (QTextBlock block = firstVisibleBlock(); block.isValid(); block = block.next()) { + if (blockBoundingGeometry(block).top() + > viewport()->height()) // only paint white spaces in the visible part of the text + break; + + const QString text = block.text(); + const int textLength = text.length(); + const int blockPosition = block.position(); + for (int i = 0; i < textLength; ++i) { + cursor.setPosition(blockPosition + i, QTextCursor::MoveAnchor); + const QRect rect = cursorRect(cursor); + + // const QFontMetrics fontMetrics = + //QFontMetrics(cursor.charFormat().font()); + + if (m_showWhiteSpaces && text.at(i) == QLatin1Char(' ')) { + if (painter.pen() != whiteSpacesPen) + painter.setPen(whiteSpacesPen); + paintSpace(painter, rect.x() + spaceWidth / 2.0, rect.y() + fontHeight / 2.0, + spaceWidth); + } else if (m_showTabulators && text.at(i) == QLatin1Char('\t')) { + if (painter.pen() != tabulatorsPen) + painter.setPen(tabulatorsPen); + paintTabstop(painter, rect.x() + spaceWidth / 2.0, rect.y() + fontHeight / 2.0, + spaceWidth); + } + } + } + painter.setPen(backupPen); } /***************************************************************************/ void TikzEditor::paintEvent(QPaintEvent *event) { - QPainter painter(viewport()); + QPainter painter(viewport()); - // highlight current line - if (m_highlightCurrentLine) - { - QRect rect = cursorRect(); - rect.setX(0); - rect.setWidth(viewport()->width()); - painter.fillRect(rect, QBrush(m_highlightCurrentLineColor)); - } + // highlight current line + if (m_highlightCurrentLine) { + QRect rect = cursorRect(); + rect.setX(0); + rect.setWidth(viewport()->width()); + painter.fillRect(rect, QBrush(m_highlightCurrentLineColor)); + } - // show white spaces and tabulators - if (m_showWhiteSpaces || m_showTabulators) - printWhiteSpaces(painter); + // show white spaces and tabulators + if (m_showWhiteSpaces || m_showTabulators) + printWhiteSpaces(painter); - painter.end(); + painter.end(); - QPlainTextEdit::paintEvent(event); + QPlainTextEdit::paintEvent(event); } void TikzEditor::goToLine(int line) { - if (line <= numOfLines()) - setCursorPosition(line, 0); + if (line <= numOfLines()) + setCursorPosition(line, 0); } void TikzEditor::setCursorPosition(int row, int col) { - const int pos = document()->findBlockByNumber(row).position() + col; - QTextCursor cursor = textCursor(); - cursor.setPosition(pos, QTextCursor::MoveAnchor); - setTextCursor(cursor); + const int pos = document()->findBlockByNumber(row).position() + col; + QTextCursor cursor = textCursor(); + cursor.setPosition(pos, QTextCursor::MoveAnchor); + setTextCursor(cursor); - // make sure that the cursor is in the middle of the visible area - centerCursor(); - setFocus(); + // make sure that the cursor is in the middle of the visible area + centerCursor(); + setFocus(); } int TikzEditor::numOfLines() const { - return document()->blockCount(); + return document()->blockCount(); } void TikzEditor::showCursorPosition() { - QTextCursor cursor = textCursor(); - Q_EMIT cursorPositionChanged(cursor.blockNumber() + 1, cursor.position() - cursor.block().position() + 1); + QTextCursor cursor = textCursor(); + Q_EMIT cursorPositionChanged(cursor.blockNumber() + 1, + cursor.position() - cursor.block().position() + 1); } /** @@ -411,234 +418,218 @@ void TikzEditor::showCursorPosition() QString TikzEditor::textUnderCursor() const { - QTextCursor cursor = textCursor(); - QTextDocument *document = this->document(); - const int startOfLine = cursor.block().position(); - int position; - for (position = cursor.position() - 1; position > 0; --position) // find the beginning of the word - { - const QChar character = document->characterAt(position); - if (character.isSpace() // if the current char is a whitespace, then we have reached the beginning of the word - || character == QLatin1Char('[') || character == QLatin1Char(',')) // these characters also delimit the beginning of the word (the beginning of a TikZ option) - { - ++position; - break; - } - else if (character == QLatin1Char('\\') || position == startOfLine) // these characters also delimit the beginning of the word (the beginning of a TikZ command) - { - break; - } - } - if (position < 0) - position = 0; - cursor.setPosition(position, QTextCursor::KeepAnchor); - return cursor.selectedText(); + QTextCursor cursor = textCursor(); + QTextDocument *document = this->document(); + const int startOfLine = cursor.block().position(); + int position; + for (position = cursor.position() - 1; position > 0; + --position) // find the beginning of the word + { + const QChar character = document->characterAt(position); + if (character.isSpace() // if the current char is a whitespace, then we have reached the + // beginning of the word + || character == QLatin1Char('[') + || character == QLatin1Char(',')) // these characters also delimit the beginning of the + // word (the beginning of a TikZ option) + { + ++position; + break; + } else if (character == QLatin1Char('\\') + || position == startOfLine) // these characters also delimit the beginning of the + // word (the beginning of a TikZ command) + { + break; + } + } + if (position < 0) + position = 0; + cursor.setPosition(position, QTextCursor::KeepAnchor); + return cursor.selectedText(); } void TikzEditor::keyPressEvent(QKeyEvent *event) { - const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers(); - - // completer - if (m_completer && m_completer->popup()->isVisible()) - { - // the following keys are forwarded by the completer to the widget - switch (event->key()) - { - case Qt::Key_Enter: - case Qt::Key_Return: - case Qt::Key_Escape: - case Qt::Key_Tab: - case Qt::Key_Backtab: - event->ignore(); - return; - } - } - - // scroll viewport when Ctrl+Up and Ctrl+Down are pressed - if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Up) - { - const int dy = -1 + verticalScrollBar()->value(); - verticalScrollBar()->setValue(dy); - } - else if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Down) - { - const int dy = 1 + verticalScrollBar()->value(); - verticalScrollBar()->setValue(dy); - } - // the first time End is pressed moves the cursor to the end of the line, the second time to the end of the block - else if (event->key() == Qt::Key_Home - && !(modifier & Qt::ControlModifier) - && !(modifier & Qt::ShiftModifier)) - { - QTextCursor cursor = textCursor(); - const int oldPosition = cursor.position(); - cursor.movePosition(QTextCursor::StartOfLine); - if (cursor.position() == oldPosition) - cursor.movePosition(QTextCursor::StartOfBlock); - setTextCursor(cursor); - ensureCursorVisible(); - } - else if (event->key() == Qt::Key_End - && !(modifier & Qt::ControlModifier) - && !(modifier & Qt::ShiftModifier)) - { - QTextCursor cursor = textCursor(); - const int oldPosition = cursor.position(); - cursor.movePosition(QTextCursor::EndOfLine); - if (cursor.position() == oldPosition) - cursor.movePosition(QTextCursor::EndOfBlock); - setTextCursor(cursor); - ensureCursorVisible(); - } - // keys that change the content without moving the cursor may alter the brackets too - else if (event->key() == Qt::Key_Delete || (event->key() == Qt::Key_Z && (modifier & Qt::ControlModifier))) - { - QPlainTextEdit::keyPressEvent(event); - highlightCurrentLine(); - matchBrackets(); // calculate new bracket highlighting - } - // go to next argument in text inserted with code completion - else if (event->key() == Qt::Key_Tab || event->key() == Qt::Key_Backtab) - { - QTextCursor cursor = textCursor(); - QTextBlock block = cursor.block(); - QTextDocument::FindFlags flags = 0; - if (event->key() == Qt::Key_Backtab) - flags = QTextDocument::FindBackward; - if (cursor.hasSelection() && cursor.selectedText().contains(QChar::ParagraphSeparator)) - { - Q_EMIT tabIndent(event->key() == Qt::Key_Backtab); - return; - } - else if (block.isValid() && block.text().contains(s_completionPlaceHolder)) - { - cursor = document()->find(s_completionPlaceHolder, cursor, flags); - if (!cursor.isNull()) - { - setTextCursor(cursor); - return; - } - } - // the following is done when there is no multiline selection and no s_completionPlaceHolder can be found - cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); - QString selectedText = cursor.selectedText(); - if (selectedText.remove(QLatin1Char(' ')).remove(QLatin1Char('\t')).isEmpty() || event->key() == Qt::Key_Backtab) - Q_EMIT tabIndent(event->key() == Qt::Key_Backtab); - else - QPlainTextEdit::keyPressEvent(event); - return; - } - else - QPlainTextEdit::keyPressEvent(event); - - // completer - if (m_completer) - { -// const QString endOfWord(QLatin1String("~!@#$%^&*()_+{}|:\"<>?,./;'[]-= ")); - const QString completionPrefix = textUnderCursor(); - if ((event->modifiers() & (Qt::ControlModifier | Qt::AltModifier)) - || (event->text().isEmpty() && event->key() != Qt::Key_AltGr) - || completionPrefix.length() < 3) -// || endOfWord.contains(event->text().right(1))) - { - m_completer->popup()->hide(); - } - else - { - if (completionPrefix != m_completer->completionPrefix()) - { - m_completer->setCompletionPrefix(completionPrefix); - m_completer->popup()->setCurrentIndex(m_completer->completionModel()->index(0, 0)); - } - if (m_completer->completionPrefix() != m_completer->currentCompletion()) -// || m_completer->completionCount() > 1) - { - QTextCursor cursor = textCursor(); -// cursor.movePosition(QTextCursor::StartOfWord); - cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, m_completer->completionPrefix().length()); - QRect rect = cursorRect(cursor); - rect.translate(5 + m_lineNumberArea->width(), 5); // reposition popup - rect.setWidth(m_completer->popup()->sizeHintForColumn(0) - + m_completer->popup()->verticalScrollBar()->sizeHint().width()); - m_completer->complete(rect); // show popup - } - else - m_completer->popup()->hide(); - } - } + const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers(); + + // completer + if (m_completer && m_completer->popup()->isVisible()) { + // the following keys are forwarded by the completer to the widget + switch (event->key()) { + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_Escape: + case Qt::Key_Tab: + case Qt::Key_Backtab: + event->ignore(); + return; + } + } + + // scroll viewport when Ctrl+Up and Ctrl+Down are pressed + if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Up) { + const int dy = -1 + verticalScrollBar()->value(); + verticalScrollBar()->setValue(dy); + } else if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Down) { + const int dy = 1 + verticalScrollBar()->value(); + verticalScrollBar()->setValue(dy); + } + // the first time End is pressed moves the cursor to the end of the line, the second time to the + // end of the block + else if (event->key() == Qt::Key_Home && !(modifier & Qt::ControlModifier) + && !(modifier & Qt::ShiftModifier)) { + QTextCursor cursor = textCursor(); + const int oldPosition = cursor.position(); + cursor.movePosition(QTextCursor::StartOfLine); + if (cursor.position() == oldPosition) + cursor.movePosition(QTextCursor::StartOfBlock); + setTextCursor(cursor); + ensureCursorVisible(); + } else if (event->key() == Qt::Key_End && !(modifier & Qt::ControlModifier) + && !(modifier & Qt::ShiftModifier)) { + QTextCursor cursor = textCursor(); + const int oldPosition = cursor.position(); + cursor.movePosition(QTextCursor::EndOfLine); + if (cursor.position() == oldPosition) + cursor.movePosition(QTextCursor::EndOfBlock); + setTextCursor(cursor); + ensureCursorVisible(); + } + // keys that change the content without moving the cursor may alter the brackets too + else if (event->key() == Qt::Key_Delete + || (event->key() == Qt::Key_Z && (modifier & Qt::ControlModifier))) { + QPlainTextEdit::keyPressEvent(event); + highlightCurrentLine(); + matchBrackets(); // calculate new bracket highlighting + } + // go to next argument in text inserted with code completion + else if (event->key() == Qt::Key_Tab || event->key() == Qt::Key_Backtab) { + QTextCursor cursor = textCursor(); + QTextBlock block = cursor.block(); + QTextDocument::FindFlags flags = 0; + if (event->key() == Qt::Key_Backtab) + flags = QTextDocument::FindBackward; + if (cursor.hasSelection() && cursor.selectedText().contains(QChar::ParagraphSeparator)) { + Q_EMIT tabIndent(event->key() == Qt::Key_Backtab); + return; + } else if (block.isValid() && block.text().contains(s_completionPlaceHolder)) { + cursor = document()->find(s_completionPlaceHolder, cursor, flags); + if (!cursor.isNull()) { + setTextCursor(cursor); + return; + } + } + // the following is done when there is no multiline selection and no s_completionPlaceHolder + // can be found + cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); + QString selectedText = cursor.selectedText(); + if (selectedText.remove(QLatin1Char(' ')).remove(QLatin1Char('\t')).isEmpty() + || event->key() == Qt::Key_Backtab) + Q_EMIT tabIndent(event->key() == Qt::Key_Backtab); + else + QPlainTextEdit::keyPressEvent(event); + return; + } else + QPlainTextEdit::keyPressEvent(event); + + // completer + if (m_completer) { + // const QString endOfWord(QLatin1String("~!@#$%^&*()_+{}|:\"<>?,./;'[]-= ")); + const QString completionPrefix = textUnderCursor(); + if ((event->modifiers() & (Qt::ControlModifier | Qt::AltModifier)) + || (event->text().isEmpty() && event->key() != Qt::Key_AltGr) + || completionPrefix.length() < 3) + // || endOfWord.contains(event->text().right(1))) + { + m_completer->popup()->hide(); + } else { + if (completionPrefix != m_completer->completionPrefix()) { + m_completer->setCompletionPrefix(completionPrefix); + m_completer->popup()->setCurrentIndex(m_completer->completionModel()->index(0, 0)); + } + if (m_completer->completionPrefix() != m_completer->currentCompletion()) + // || m_completer->completionCount() > 1) + { + QTextCursor cursor = textCursor(); + // cursor.movePosition(QTextCursor::StartOfWord); + cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, + m_completer->completionPrefix().length()); + QRect rect = cursorRect(cursor); + rect.translate(5 + m_lineNumberArea->width(), 5); // reposition popup + rect.setWidth(m_completer->popup()->sizeHintForColumn(0) + + m_completer->popup()->verticalScrollBar()->sizeHint().width()); + m_completer->complete(rect); // show popup + } else + m_completer->popup()->hide(); + } + } } void TikzEditor::focusInEvent(QFocusEvent *event) { - if (m_completer) - m_completer->setWidget(this); + if (m_completer) + m_completer->setWidget(this); - Q_EMIT focusIn(); + Q_EMIT focusIn(); - QPlainTextEdit::focusInEvent(event); + QPlainTextEdit::focusInEvent(event); } void TikzEditor::focusOutEvent(QFocusEvent *event) { - Q_EMIT focusOut(); - QPlainTextEdit::focusOutEvent(event); + Q_EMIT focusOut(); + QPlainTextEdit::focusOutEvent(event); } /***************************************************************************/ void TikzEditor::updateCompleter(bool useCompletion, const QStringList &words) { - if (!useCompletion) - { - if (m_completer) - disconnect(m_completer, 0, this, 0); - delete m_completer; - m_completer = 0; - return; - } - - if (!m_completer) - { - m_completer = new QCompleter(this); - m_completer->setWidget(this); - m_completer->setCompletionMode(QCompleter::PopupCompletion); - m_completer->setCaseSensitivity(Qt::CaseInsensitive); - m_completer->setWrapAround(false); - connect(m_completer, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); - } - - QStringListModel *model = new QStringListModel(words, m_completer); - m_completer->setModel(model); - m_completer->setModelSorting(QCompleter::CaseSensitivelySortedModel); + if (!useCompletion) { + if (m_completer) + disconnect(m_completer, 0, this, 0); + delete m_completer; + m_completer = 0; + return; + } + + if (!m_completer) { + m_completer = new QCompleter(this); + m_completer->setWidget(this); + m_completer->setCompletionMode(QCompleter::PopupCompletion); + m_completer->setCaseSensitivity(Qt::CaseInsensitive); + m_completer->setWrapAround(false); + connect(m_completer, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); + } + + QStringListModel *model = new QStringListModel(words, m_completer); + m_completer->setModel(model); + m_completer->setModelSorting(QCompleter::CaseSensitivelySortedModel); } void TikzEditor::insertCompletion(const QString &completion) { - if (!m_completer || m_completer->widget() != this) - return; + if (!m_completer || m_completer->widget() != this) + return; - Q_EMIT showStatusMessage(completion, 0); + Q_EMIT showStatusMessage(completion, 0); - QTextCursor cursor = textCursor(); - const int extra = completion.length() - m_completer->completionPrefix().length(); - const int pos = cursor.position(); + QTextCursor cursor = textCursor(); + const int extra = completion.length() - m_completer->completionPrefix().length(); + const int pos = cursor.position(); - // remove all options (between <...>) and put cursor at the first option - QString insertWord = completion.right(extra); - const QRegExp rx(QLatin1String("<[^<>]*>")); - const int offset = rx.indexIn(insertWord) - 1; // put cursor at the first option - insertWord.replace(rx, s_completionPlaceHolder); + // remove all options (between <...>) and put cursor at the first option + QString insertWord = completion.right(extra); + const QRegExp rx(QLatin1String("<[^<>]*>")); + const int offset = rx.indexIn(insertWord) - 1; // put cursor at the first option + insertWord.replace(rx, s_completionPlaceHolder); - cursor.insertText(insertWord); - if (insertWord.contains(s_completionPlaceHolder)) - { - cursor.setPosition(pos, QTextCursor::MoveAnchor); - cursor = document()->find(s_completionPlaceHolder, cursor); - } - else if (offset > 0) - cursor.setPosition(pos + offset + 1, QTextCursor::MoveAnchor); - setTextCursor(cursor); + cursor.insertText(insertWord); + if (insertWord.contains(s_completionPlaceHolder)) { + cursor.setPosition(pos, QTextCursor::MoveAnchor); + cursor = document()->find(s_completionPlaceHolder, cursor); + } else if (offset > 0) + cursor.setPosition(pos + offset + 1, QTextCursor::MoveAnchor); + setTextCursor(cursor); } /***************************************************************************/ @@ -650,31 +641,28 @@ void TikzEditor::insertCompletion(const QString &completion) */ void TikzEditor::toggleUserBookmark(int lineNumber) { - if (lineNumber <= 0 || lineNumber > document()->blockCount()) - return; - for (int i = 0; i < m_userBookmarks.length(); ++i) - { - if (m_userBookmarks.at(i) == lineNumber) - { - m_userBookmarks.removeAt(i); - m_lineNumberArea->update(); - return; - } - else if (m_userBookmarks.at(i) > lineNumber) - { - m_userBookmarks.insert(i, lineNumber); - m_lineNumberArea->update(); - return; - } - } - m_userBookmarks.append(lineNumber); // if lineNumber is larger than any number already in the list, then we insert lineNumber at the end of the list - m_lineNumberArea->update(); + if (lineNumber <= 0 || lineNumber > document()->blockCount()) + return; + for (int i = 0; i < m_userBookmarks.length(); ++i) { + if (m_userBookmarks.at(i) == lineNumber) { + m_userBookmarks.removeAt(i); + m_lineNumberArea->update(); + return; + } else if (m_userBookmarks.at(i) > lineNumber) { + m_userBookmarks.insert(i, lineNumber); + m_lineNumberArea->update(); + return; + } + } + m_userBookmarks.append(lineNumber); // if lineNumber is larger than any number already in the + // list, then we insert lineNumber at the end of the list + m_lineNumberArea->update(); } void TikzEditor::toggleUserBookmark() { - const int lineNumber = textCursor().blockNumber() + 1; - toggleUserBookmark(lineNumber); + const int lineNumber = textCursor().blockNumber() + 1; + toggleUserBookmark(lineNumber); } /*! @@ -684,33 +672,29 @@ void TikzEditor::toggleUserBookmark() int TikzEditor::userBookmark(int which) const { - return which >= 0 && which < m_userBookmarks.length() ? m_userBookmarks.at(which) : -1; + return which >= 0 && which < m_userBookmarks.length() ? m_userBookmarks.at(which) : -1; } void TikzEditor::previousUserBookmark() { - const int lineNumber = textCursor().blockNumber() + 1; - for (int i = m_userBookmarks.length() - 1; i >= 0; --i) - { - if (lineNumber > m_userBookmarks.at(i)) - { - goToLine(m_userBookmarks.at(i) - 1); - return; - } - } + const int lineNumber = textCursor().blockNumber() + 1; + for (int i = m_userBookmarks.length() - 1; i >= 0; --i) { + if (lineNumber > m_userBookmarks.at(i)) { + goToLine(m_userBookmarks.at(i) - 1); + return; + } + } } void TikzEditor::nextUserBookmark() { - const int lineNumber = textCursor().blockNumber() + 1; - for (int i = 0; i < m_userBookmarks.length(); ++i) - { - if (lineNumber < m_userBookmarks.at(i)) - { - goToLine(m_userBookmarks.at(i) - 1); - return; - } - } + const int lineNumber = textCursor().blockNumber() + 1; + for (int i = 0; i < m_userBookmarks.length(); ++i) { + if (lineNumber < m_userBookmarks.at(i)) { + goToLine(m_userBookmarks.at(i) - 1); + return; + } + } } /*! @@ -722,80 +706,78 @@ void TikzEditor::nextUserBookmark() void TikzEditor::recalculateBookmarks(int position) { - const int addedLines = numOfLines() - m_oldNumOfLines; - const int lineNumber = document()->findBlock(position).blockNumber() + 1; - if (addedLines != 0) - { - for (int i = 0; i < m_userBookmarks.length(); ++i) - { - // if a line containing a bookmark is removed, then the bookmark itself must also be removed - if (addedLines < 0 && lineNumber <= m_userBookmarks.at(i) - && lineNumber - addedLines > m_userBookmarks.at(i)) - { - m_userBookmarks.removeAt(i); - --i; - } - else if (lineNumber <= m_userBookmarks.at(i)) // shift all bookmarks that come after the insertion or deletion of lines - m_userBookmarks[i] += addedLines; - } - } - m_oldNumOfLines = numOfLines(); + const int addedLines = numOfLines() - m_oldNumOfLines; + const int lineNumber = document()->findBlock(position).blockNumber() + 1; + if (addedLines != 0) { + for (int i = 0; i < m_userBookmarks.length(); ++i) { + // if a line containing a bookmark is removed, then the bookmark itself must also be + // removed + if (addedLines < 0 && lineNumber <= m_userBookmarks.at(i) + && lineNumber - addedLines > m_userBookmarks.at(i)) { + m_userBookmarks.removeAt(i); + --i; + } else if (lineNumber <= m_userBookmarks.at(i)) // shift all bookmarks that come after + // the insertion or deletion of lines + m_userBookmarks[i] += addedLines; + } + } + m_oldNumOfLines = numOfLines(); } QList TikzEditor::userBookmarks() const { - return m_userBookmarks; + return m_userBookmarks; } void TikzEditor::setUserBookmarks(const QList &bookmarks) { - m_userBookmarks.clear(); - for (int i = 0; i < bookmarks.length(); ++i) - { - if (bookmarks.at(i) > 0 && bookmarks.at(i) <= numOfLines()) - toggleUserBookmark(bookmarks.at(i)); - } + m_userBookmarks.clear(); + for (int i = 0; i < bookmarks.length(); ++i) { + if (bookmarks.at(i) > 0 && bookmarks.at(i) <= numOfLines()) + toggleUserBookmark(bookmarks.at(i)); + } } /***************************************************************************/ int TikzEditor::lineNumberAreaWidth() { - int digits = 1; - for (int max = qMax(1, blockCount()); max >= 10; max /= 10) - ++digits; - digits = qMax(4, digits) + 1; + int digits = 1; + for (int max = qMax(1, blockCount()); max >= 10; max /= 10) + ++digits; + digits = qMax(4, digits) + 1; - return m_showLineNumberArea ? 3 + fontMetrics().width(QLatin1Char('9')) * digits : 0; + return m_showLineNumberArea ? 3 + fontMetrics().width(QLatin1Char('9')) * digits : 0; } void TikzEditor::updateLineNumberAreaWidth() { - setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); + setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void TikzEditor::updateLineNumberArea(const QRect &rect, int dy) { - if (dy) - m_lineNumberArea->scroll(0, dy); - else - m_lineNumberArea->update(0, rect.y(), m_lineNumberArea->width(), rect.height()); + if (dy) + m_lineNumberArea->scroll(0, dy); + else + m_lineNumberArea->update(0, rect.y(), m_lineNumberArea->width(), rect.height()); - if (rect.contains(viewport()->rect())) - updateLineNumberAreaWidth(); + if (rect.contains(viewport()->rect())) + updateLineNumberAreaWidth(); } void TikzEditor::resizeEvent(QResizeEvent *event) { - QPlainTextEdit::resizeEvent(event); + QPlainTextEdit::resizeEvent(event); - QRect rect = contentsRect(); - m_lineNumberArea->setGeometry(QRect(rect.left(), rect.top(), lineNumberAreaWidth(), rect.height())); + QRect rect = contentsRect(); + m_lineNumberArea->setGeometry( + QRect(rect.left(), rect.top(), lineNumberAreaWidth(), rect.height())); } void TikzEditor::setShowLineNumberArea(bool visible) { - m_showLineNumberArea = visible; - m_lineNumberArea->setVisible(visible); - updateLineNumberAreaWidth(); + m_showLineNumberArea = visible; + m_lineNumberArea->setVisible(visible); + updateLineNumberAreaWidth(); } diff --git a/app/tikzeditor.h b/app/tikzeditor.h index 4e51280..08aeff0 100644 --- a/app/tikzeditor.h +++ b/app/tikzeditor.h @@ -29,89 +29,89 @@ class QString; class TikzEditor : public QPlainTextEdit { - Q_OBJECT - Q_PROPERTY(int numOfLines READ numOfLines) + Q_OBJECT + Q_PROPERTY(int numOfLines READ numOfLines) public: - explicit TikzEditor(QWidget *parent = 0); - ~TikzEditor(); - void setShowWhiteSpaces(bool visible); - void setShowTabulators(bool visible); - void setShowMatchingBrackets(bool visible); - void setHighlightCurrentLine(bool visible); - void setWhiteSpacesColor(const QColor &color); - void setTabulatorsColor(const QColor &color); - void setMatchingColor(const QColor &color); - void setHighlightCurrentLineColor(const QColor &color); - void goToLine(int line); - int numOfLines() const; - void updateCompleter(bool useCompletion, const QStringList &words); - - void toggleUserBookmark(int lineNumber); - int userBookmark(int which) const; - QList userBookmarks() const; - void setUserBookmarks(const QList &bookmarks); - - void setShowLineNumberArea(bool visible); - friend class LineNumberWidget; + explicit TikzEditor(QWidget *parent = 0); + ~TikzEditor(); + void setShowWhiteSpaces(bool visible); + void setShowTabulators(bool visible); + void setShowMatchingBrackets(bool visible); + void setHighlightCurrentLine(bool visible); + void setWhiteSpacesColor(const QColor &color); + void setTabulatorsColor(const QColor &color); + void setMatchingColor(const QColor &color); + void setHighlightCurrentLineColor(const QColor &color); + void goToLine(int line); + int numOfLines() const; + void updateCompleter(bool useCompletion, const QStringList &words); + + void toggleUserBookmark(int lineNumber); + int userBookmark(int which) const; + QList userBookmarks() const; + void setUserBookmarks(const QList &bookmarks); + + void setShowLineNumberArea(bool visible); + friend class LineNumberWidget; public Q_SLOTS: - void showCursorPosition(); - void toggleUserBookmark(); - void previousUserBookmark(); - void nextUserBookmark(); + void showCursorPosition(); + void toggleUserBookmark(); + void previousUserBookmark(); + void nextUserBookmark(); Q_SIGNALS: - void cursorPositionChanged(int row, int col); - void showStatusMessage(const QString &message, int timeout = 3000); - void focusIn(); - void focusOut(); - void tabIndent(bool isUnindenting); + void cursorPositionChanged(int row, int col); + void showStatusMessage(const QString &message, int timeout = 3000); + void focusIn(); + void focusOut(); + void tabIndent(bool isUnindenting); protected: - void paintEvent(QPaintEvent *event); - void keyPressEvent(QKeyEvent *event); - void focusInEvent(QFocusEvent *event); - void focusOutEvent(QFocusEvent *event); - int lineNumberAreaWidth(); - void resizeEvent(QResizeEvent *event); + void paintEvent(QPaintEvent *event); + void keyPressEvent(QKeyEvent *event); + void focusInEvent(QFocusEvent *event); + void focusOutEvent(QFocusEvent *event); + int lineNumberAreaWidth(); + void resizeEvent(QResizeEvent *event); private Q_SLOTS: - void highlightCurrentLine(); - void matchBrackets(); - void insertCompletion(const QString &completion); - void recalculateBookmarks(int position); - void updateLineNumberAreaWidth(); - void updateLineNumberArea(const QRect &rect, int dy); + void highlightCurrentLine(); + void matchBrackets(); + void insertCompletion(const QString &completion); + void recalculateBookmarks(int position); + void updateLineNumberAreaWidth(); + void updateLineNumberArea(const QRect &rect, int dy); private: - void showMatchingBrackets(int matchingBegin, int matchingEnd); - void paintTabstop(QPainter &painter, qreal x, qreal y, int spaceWidth); - void paintSpace(QPainter &painter, qreal x, qreal y, int spaceWidth); - void printWhiteSpaces(QPainter &painter); - QString textUnderCursor() const; - void setCursorPosition(int row, int col); - - QColor m_highlightCurrentLineColor; - QRect m_previousHighlightedLine; - bool m_highlightCurrentLine; - int m_oldVerticalScrollBarValue; - - QString m_plainText; - QColor m_whiteSpacesColor; - QColor m_tabulatorsColor; - QColor m_matchingColor; - bool m_showWhiteSpaces; - bool m_showTabulators; - bool m_showMatchingBrackets; - - QCompleter *m_completer; - - QList m_userBookmarks; - int m_oldNumOfLines; - - QWidget *m_lineNumberArea; - bool m_showLineNumberArea; + void showMatchingBrackets(int matchingBegin, int matchingEnd); + void paintTabstop(QPainter &painter, qreal x, qreal y, int spaceWidth); + void paintSpace(QPainter &painter, qreal x, qreal y, int spaceWidth); + void printWhiteSpaces(QPainter &painter); + QString textUnderCursor() const; + void setCursorPosition(int row, int col); + + QColor m_highlightCurrentLineColor; + QRect m_previousHighlightedLine; + bool m_highlightCurrentLine; + int m_oldVerticalScrollBarValue; + + QString m_plainText; + QColor m_whiteSpacesColor; + QColor m_tabulatorsColor; + QColor m_matchingColor; + bool m_showWhiteSpaces; + bool m_showTabulators; + bool m_showMatchingBrackets; + + QCompleter *m_completer; + + QList m_userBookmarks; + int m_oldNumOfLines; + + QWidget *m_lineNumberArea; + bool m_showLineNumberArea; }; #endif diff --git a/app/tikzeditorhighlighter.cpp b/app/tikzeditorhighlighter.cpp index c1b09cc..5cc58fe 100644 --- a/app/tikzeditorhighlighter.cpp +++ b/app/tikzeditorhighlighter.cpp @@ -25,163 +25,163 @@ #include "tikzeditorhighlighter.h" #include "tikzcommandinserter.h" -TikzHighlighter::TikzHighlighter(QTextDocument *parent) - : QSyntaxHighlighter(parent) -{ -} +TikzHighlighter::TikzHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { } -TikzHighlighter::~TikzHighlighter() -{ -} +TikzHighlighter::~TikzHighlighter() { } void TikzHighlighter::setHighlightingRules(const QVector &highlightingRules) { - m_highlightingRules << highlightingRules; - - // add highlighting for environments and comments - HighlightingRule rule; - QStringList highlightTypeNames = getHighlightTypeNames(); - const int currentIndex = highlightTypeNames.size() - 2; - // environments - QStringList keywordPatterns; - keywordPatterns << QLatin1String("\\\\begin\\{[^\\}]*\\}") << QLatin1String("\\\\end\\{[^\\}]*\\}"); - Q_FOREACH (const QString &pattern, keywordPatterns) - { - rule.type = highlightTypeNames.at(currentIndex); - rule.pattern = QRegExp(pattern); - rule.isRegExp = true; - m_highlightingRules.append(rule); - } - // comments - rule.type = highlightTypeNames.at(currentIndex + 1); - rule.pattern = QRegExp(QLatin1String("%[^\n]*")); - rule.isRegExp = true; - m_highlightingRules.append(rule); - -// m_formatList = getDefaultHighlightFormats(); + m_highlightingRules << highlightingRules; + + // add highlighting for environments and comments + HighlightingRule rule; + QStringList highlightTypeNames = getHighlightTypeNames(); + const int currentIndex = highlightTypeNames.size() - 2; + // environments + QStringList keywordPatterns; + keywordPatterns << QLatin1String("\\\\begin\\{[^\\}]*\\}") + << QLatin1String("\\\\end\\{[^\\}]*\\}"); + Q_FOREACH (const QString &pattern, keywordPatterns) { + rule.type = highlightTypeNames.at(currentIndex); + rule.pattern = QRegExp(pattern); + rule.isRegExp = true; + m_highlightingRules.append(rule); + } + // comments + rule.type = highlightTypeNames.at(currentIndex + 1); + rule.pattern = QRegExp(QLatin1String("%[^\n]*")); + rule.isRegExp = true; + m_highlightingRules.append(rule); + + // m_formatList = getDefaultHighlightFormats(); } /***************************************************************************/ QMap TikzHighlighter::getDefaultHighlightFormats() { - QMap formatList = TikzCommandInserter::getDefaultHighlightFormats(); - QStringList highlightTypeNames = getHighlightTypeNames(); - const int currentIndex = highlightTypeNames.size() - 2; - - // format for environments - QTextCharFormat keywordFormat; - keywordFormat.setForeground(Qt::darkBlue); - keywordFormat.setFont(qApp->font()); - keywordFormat.setFontWeight(QFont::Bold); - formatList[highlightTypeNames.at(currentIndex)] = keywordFormat; - - // format for comments - QTextCharFormat commentFormat; - commentFormat.setForeground(Qt::gray); - commentFormat.setFont(qApp->font()); - commentFormat.setFontWeight(QFont::Normal); - formatList[highlightTypeNames.at(currentIndex + 1)] = commentFormat; - - return formatList; + QMap formatList = TikzCommandInserter::getDefaultHighlightFormats(); + QStringList highlightTypeNames = getHighlightTypeNames(); + const int currentIndex = highlightTypeNames.size() - 2; + + // format for environments + QTextCharFormat keywordFormat; + keywordFormat.setForeground(Qt::darkBlue); + keywordFormat.setFont(qApp->font()); + keywordFormat.setFontWeight(QFont::Bold); + formatList[highlightTypeNames.at(currentIndex)] = keywordFormat; + + // format for comments + QTextCharFormat commentFormat; + commentFormat.setForeground(Qt::gray); + commentFormat.setFont(qApp->font()); + commentFormat.setFontWeight(QFont::Normal); + formatList[highlightTypeNames.at(currentIndex + 1)] = commentFormat; + + return formatList; } QStringList TikzHighlighter::getTranslatedHighlightTypeNames() { - QStringList translatedHighlightTypeNames = TikzCommandInserter::getTranslatedHighlightTypeNames(); - translatedHighlightTypeNames << tr("Environments") << tr("Comments"); - return translatedHighlightTypeNames; + QStringList translatedHighlightTypeNames = + TikzCommandInserter::getTranslatedHighlightTypeNames(); + translatedHighlightTypeNames << tr("Environments") << tr("Comments"); + return translatedHighlightTypeNames; } QStringList TikzHighlighter::getHighlightTypeNames() { - QStringList highlightTypeNames = TikzCommandInserter::getHighlightTypeNames(); - highlightTypeNames << QLatin1String("Environments") << QLatin1String("Comments"); - return highlightTypeNames; + QStringList highlightTypeNames = TikzCommandInserter::getHighlightTypeNames(); + highlightTypeNames << QLatin1String("Environments") << QLatin1String("Comments"); + return highlightTypeNames; } /***************************************************************************/ void TikzHighlighter::applySettings() { - QSettings settings; - settings.beginGroup(QLatin1String("Highlighting")); - const bool customHighlighting = settings.value(QLatin1String("Customize"), true).toBool(); - - m_formatList.clear(); - m_formatList = getDefaultHighlightFormats(); - - if (customHighlighting) - { - const int numOfRules = settings.value(QLatin1String("Number"), 0).toInt(); - for (int i = 0; i < numOfRules; ++i) - { - const QString name = settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Name")).toString(); - const QString colorName = settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Color")).toString(); - const QString fontName = settings.value(QLatin1String("Item") + QString::number(i) + QLatin1String("/Font")).toString(); - QFont font; - font.fromString(fontName); - QTextCharFormat format; - format.setForeground(QBrush(QColor(colorName))); - format.setFont(font); - m_formatList[name] = format; - } - } - settings.endGroup(); + QSettings settings; + settings.beginGroup(QLatin1String("Highlighting")); + const bool customHighlighting = settings.value(QLatin1String("Customize"), true).toBool(); + + m_formatList.clear(); + m_formatList = getDefaultHighlightFormats(); + + if (customHighlighting) { + const int numOfRules = settings.value(QLatin1String("Number"), 0).toInt(); + for (int i = 0; i < numOfRules; ++i) { + const QString name = settings.value(QLatin1String("Item") + QString::number(i) + + QLatin1String("/Name")) + .toString(); + const QString colorName = settings.value(QLatin1String("Item") + QString::number(i) + + QLatin1String("/Color")) + .toString(); + const QString fontName = settings.value(QLatin1String("Item") + QString::number(i) + + QLatin1String("/Font")) + .toString(); + QFont font; + font.fromString(fontName); + QTextCharFormat format; + format.setForeground(QBrush(QColor(colorName))); + format.setFont(font); + m_formatList[name] = format; + } + } + settings.endGroup(); } namespace { int indexOf(const QString &text, const QString &tag, int startPos = 0) { - // valgrind --tool=callgrind --zero-before="MainWindow::loadUrl(Url const&)" gives a small win for this function over "text.indexOf(tag, startPos);" - const int textLength = text.length(); - const int tagLength = tag.length(); - for (int i = startPos, j = 0; i < textLength && j < tagLength; ++i, ++j) - { - if (text.at(i) != tag.at(j)) - { - j = -1; - continue; - } - if (j == tagLength - 1) - return i - tagLength + 1; - } - return -1; + // valgrind --tool=callgrind --zero-before="MainWindow::loadUrl(Url const&)" gives a small win + // for this function over "text.indexOf(tag, startPos);" + const int textLength = text.length(); + const int tagLength = tag.length(); + for (int i = startPos, j = 0; i < textLength && j < tagLength; ++i, ++j) { + if (text.at(i) != tag.at(j)) { + j = -1; + continue; + } + if (j == tagLength - 1) + return i - tagLength + 1; + } + return -1; } } // anonymous namespace void TikzHighlighter::highlightBlock(const QString &text) { - // Try each highlighting pattern and apply formatting if it matches - // Having the outer loop loop over the highlighting rules and the inner loop over the text is much faster than conversely - Q_FOREACH (const HighlightingRule &rule, m_highlightingRules) - { - if (!rule.isRegExp) // match the insertion string - { - const int length = rule.matchString.length(); -// int index = text.indexOf(rule.matchString); - int index = indexOf(text, rule.matchString); - while (index >= 0) - { - if (index == 0 || text.at(index - 1) != QLatin1Char('\\')) // avoid matching e.g. "node" as an option if in reality "\node" as a command is written - setFormat(index, length, m_formatList[rule.type]); -// index = text.indexOf(rule.matchString, index + length); - index = indexOf(text, rule.matchString, index + length); - } - } - else // match the pattern - { - int index = rule.pattern.indexIn(text); - while (index >= 0) - { - const int length = rule.pattern.matchedLength(); - if (index == 0 || text.at(index-1) != QLatin1Char('\\')) - setFormat(index, length, m_formatList[rule.type]); - index = rule.pattern.indexIn(text, index + length); - } - } - } - setCurrentBlockState(0); + // Try each highlighting pattern and apply formatting if it matches + // Having the outer loop loop over the highlighting rules and the inner loop over the text is + // much faster than conversely + Q_FOREACH (const HighlightingRule &rule, m_highlightingRules) { + if (!rule.isRegExp) // match the insertion string + { + const int length = rule.matchString.length(); + // int index = text.indexOf(rule.matchString); + int index = indexOf(text, rule.matchString); + while (index >= 0) { + if (index == 0 + || text.at(index - 1) + != QLatin1Char('\\')) // avoid matching e.g. "node" as an option if in + // reality "\node" as a command is written + setFormat(index, length, m_formatList[rule.type]); + // index = text.indexOf(rule.matchString, index + + //length); + index = indexOf(text, rule.matchString, index + length); + } + } else // match the pattern + { + int index = rule.pattern.indexIn(text); + while (index >= 0) { + const int length = rule.pattern.matchedLength(); + if (index == 0 || text.at(index - 1) != QLatin1Char('\\')) + setFormat(index, length, m_formatList[rule.type]); + index = rule.pattern.indexIn(text, index + length); + } + } + } + setCurrentBlockState(0); } diff --git a/app/tikzeditorhighlighter.h b/app/tikzeditorhighlighter.h index 5e2109a..99edee5 100644 --- a/app/tikzeditorhighlighter.h +++ b/app/tikzeditorhighlighter.h @@ -25,10 +25,10 @@ struct HighlightingRule { - QString type; /// The name of the formatting type - QString matchString; /// The string to match for formatting; only used when pattern is empty - QRegExp pattern; /// The pattern to match for formatting; overrides usage of matchString - bool isRegExp; + QString type; /// The name of the formatting type + QString matchString; /// The string to match for formatting; only used when pattern is empty + QRegExp pattern; /// The pattern to match for formatting; overrides usage of matchString + bool isRegExp; }; /** A simple highlighter for the TikZ graphics programming language @@ -36,30 +36,30 @@ struct HighlightingRule */ class TikzHighlighter : public QSyntaxHighlighter { - Q_OBJECT + Q_OBJECT public: - explicit TikzHighlighter(QTextDocument *parent = 0); - virtual ~TikzHighlighter(); + explicit TikzHighlighter(QTextDocument *parent = 0); + virtual ~TikzHighlighter(); - void setHighlightingRules(const QVector &highlightingRules); - static QMap getDefaultHighlightFormats(); - static QStringList getTranslatedHighlightTypeNames(); - static QStringList getHighlightTypeNames(); - void applySettings(); + void setHighlightingRules(const QVector &highlightingRules); + static QMap getDefaultHighlightFormats(); + static QStringList getTranslatedHighlightTypeNames(); + static QStringList getHighlightTypeNames(); + void applySettings(); protected: - /** Implements QSyntaxHighlighter::highlightBlock() - * @see QSyntaxHighlighter::highlightBlock() - */ - void highlightBlock(const QString &text); + /** Implements QSyntaxHighlighter::highlightBlock() + * @see QSyntaxHighlighter::highlightBlock() + */ + void highlightBlock(const QString &text); private: - /// All highlighting rules with their formatting for easy iteration - QVector m_highlightingRules; + /// All highlighting rules with their formatting for easy iteration + QVector m_highlightingRules; - QMap m_formatList; - QStringList m_highlightTypeNames; + QMap m_formatList; + QStringList m_highlightTypeNames; }; #endif diff --git a/app/tikzeditorview.cpp b/app/tikzeditorview.cpp index b0b8205..861925c 100644 --- a/app/tikzeditorview.cpp +++ b/app/tikzeditorview.cpp @@ -33,293 +33,345 @@ #include "editreplacewidget.h" #include "editreplacecurrentwidget.h" #include "tikzeditor.h" -//#include "tikzeditorhighlighter.h" +// #include "tikzeditorhighlighter.h" #include "../common/utils/action.h" #include "../common/utils/icon.h" #include "../common/utils/messagebox.h" #include "../common/utils/standardaction.h" TikzEditorView::TikzEditorView(QWidget *parent) - : TikzEditorViewAbstract(parent) - , m_goToLineWidget(0) - , m_indentWidget(0) - , m_replaceWidget(0) - , m_replaceCurrentWidget(0) -{ - m_tikzEditor = new TikzEditor(this); - m_tikzEditor->setWhatsThis(tr("

Enter your TikZ code here. " - "The code should begin with \\begin{tikzpicture} and end with " - "\\end{tikzpicture}.

")); -/* - commandInserter = new TikzCommandInserter(tikzEditor, this); - tikzHighlighter = new TikzHighlighter(commandInserter, tikzEditor->document()); - tikzHighlighter->rehighlight(); // avoid that textEdit emits the signal contentsChanged() when it is still empty - tikzController = new TikzPngPreviewer(textEdit); -*/ - - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setMargin(0); - mainLayout->addWidget(m_tikzEditor); - - createActions(); - - connect(m_tikzEditor->document(), SIGNAL(modificationChanged(bool)), - this, SIGNAL(modificationChanged(bool))); - connect(m_tikzEditor->document(), SIGNAL(contentsChanged()), - this, SIGNAL(contentsChanged())); - connect(m_tikzEditor, SIGNAL(cursorPositionChanged(int,int)), - this, SIGNAL(cursorPositionChanged(int,int))); - connect(m_tikzEditor, SIGNAL(showStatusMessage(QString,int)), - this, SIGNAL(showStatusMessage(QString,int))); - connect(m_tikzEditor, SIGNAL(tabIndent(bool)), - this, SLOT(tabIndent(bool))); - - connect(m_tikzEditor, SIGNAL(focusIn()), - this, SIGNAL(focusIn())); - connect(m_tikzEditor, SIGNAL(focusOut()), - this, SIGNAL(focusOut())); + : TikzEditorViewAbstract(parent), + m_goToLineWidget(0), + m_indentWidget(0), + m_replaceWidget(0), + m_replaceCurrentWidget(0) +{ + m_tikzEditor = new TikzEditor(this); + m_tikzEditor->setWhatsThis(tr("

Enter your TikZ code here. " + "The code should begin with \\begin{tikzpicture} and end with " + "\\end{tikzpicture}.

")); + /* + commandInserter = new TikzCommandInserter(tikzEditor, this); + tikzHighlighter = new TikzHighlighter(commandInserter, tikzEditor->document()); + tikzHighlighter->rehighlight(); // avoid that textEdit emits the signal + contentsChanged() when it is still empty tikzController = new TikzPngPreviewer(textEdit); + */ + + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setMargin(0); + mainLayout->addWidget(m_tikzEditor); + + createActions(); + + connect(m_tikzEditor->document(), SIGNAL(modificationChanged(bool)), this, + SIGNAL(modificationChanged(bool))); + connect(m_tikzEditor->document(), SIGNAL(contentsChanged()), this, SIGNAL(contentsChanged())); + connect(m_tikzEditor, SIGNAL(cursorPositionChanged(int, int)), this, + SIGNAL(cursorPositionChanged(int, int))); + connect(m_tikzEditor, SIGNAL(showStatusMessage(QString, int)), this, + SIGNAL(showStatusMessage(QString, int))); + connect(m_tikzEditor, SIGNAL(tabIndent(bool)), this, SLOT(tabIndent(bool))); + + connect(m_tikzEditor, SIGNAL(focusIn()), this, SIGNAL(focusIn())); + connect(m_tikzEditor, SIGNAL(focusOut()), this, SIGNAL(focusOut())); } TikzEditorView::~TikzEditorView() { -// tikzHighlighter->deleteLater(); + // tikzHighlighter->deleteLater(); } QPlainTextEdit *TikzEditorView::editor() { - return m_tikzEditor; + return m_tikzEditor; } QTextDocument *TikzEditorView::document() { - return m_tikzEditor->document(); + return m_tikzEditor->document(); } QString TikzEditorView::text() { - return m_tikzEditor->document()->toPlainText(); + return m_tikzEditor->document()->toPlainText(); } void TikzEditorView::setFont(const QFont &editorFont) { -// m_tikzEditor->setFont(editorFont); - // Setting a stylesheet is faster than using QPlainTextEdit::setFont() (according to valgrind), so here we go: - QString fontStyle; - QString fontWeight; - QString fontDecoration; - switch (editorFont.style()) - { - case QFont::StyleItalic: fontStyle = QLatin1String("italic;"); break; - case QFont::StyleOblique: fontStyle = QLatin1String("oblique;"); break; - default: fontStyle = QLatin1String("normal;"); break; - } - switch (editorFont.weight()) - { - case QFont::Light: fontWeight = QLatin1String("250;"); break; - case QFont::Normal: fontWeight = QLatin1String("normal;"); break; // 400 according to http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight - case QFont::DemiBold: fontWeight = QLatin1String("550;"); break; - case QFont::Bold: fontWeight = QLatin1String("bold;"); break; // 700 - case QFont::Black: fontWeight = QLatin1String("850;"); break; - default: fontWeight = QLatin1String("normal;"); break; - } - if (editorFont.underline()) - fontDecoration = QLatin1String("underline"); - else if (editorFont.strikeOut()) - fontDecoration = QLatin1String("line-through"); - else - fontDecoration = QLatin1String("none"); - m_tikzEditor->setStyleSheet(QString(QLatin1String("QPlainTextEdit { font-family: %1; font-size: %2; font-style: %3; font-weight: %4; text-decoration: %5; }")) - .arg(editorFont.family()) - .arg(editorFont.pointSize()) - .arg(fontStyle) - .arg(fontWeight) - .arg(fontDecoration)); - - // XXX dirty hack: make sure the correct font size is set, the stylesheet seems to ignore font sizes :( - QTextCharFormat fm = m_tikzEditor->currentCharFormat(); - fm.setFontPointSize(editorFont.pointSize()); - m_tikzEditor->setCurrentCharFormat(fm); - - m_tikzEditor->setTabStopWidth(m_tikzEditor->fontMetrics().width(QLatin1String(" "))); + // m_tikzEditor->setFont(editorFont); + // Setting a stylesheet is faster than using QPlainTextEdit::setFont() (according to valgrind), + // so here we go: + QString fontStyle; + QString fontWeight; + QString fontDecoration; + switch (editorFont.style()) { + case QFont::StyleItalic: + fontStyle = QLatin1String("italic;"); + break; + case QFont::StyleOblique: + fontStyle = QLatin1String("oblique;"); + break; + default: + fontStyle = QLatin1String("normal;"); + break; + } + switch (editorFont.weight()) { + case QFont::Light: + fontWeight = QLatin1String("250;"); + break; + case QFont::Normal: + fontWeight = QLatin1String("normal;"); + break; // 400 according to http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight + case QFont::DemiBold: + fontWeight = QLatin1String("550;"); + break; + case QFont::Bold: + fontWeight = QLatin1String("bold;"); + break; // 700 + case QFont::Black: + fontWeight = QLatin1String("850;"); + break; + default: + fontWeight = QLatin1String("normal;"); + break; + } + if (editorFont.underline()) + fontDecoration = QLatin1String("underline"); + else if (editorFont.strikeOut()) + fontDecoration = QLatin1String("line-through"); + else + fontDecoration = QLatin1String("none"); + m_tikzEditor->setStyleSheet( + QString(QLatin1String("QPlainTextEdit { font-family: %1; font-size: %2; font-style: " + "%3; font-weight: %4; text-decoration: %5; }")) + .arg(editorFont.family()) + .arg(editorFont.pointSize()) + .arg(fontStyle) + .arg(fontWeight) + .arg(fontDecoration)); + + // XXX dirty hack: make sure the correct font size is set, the stylesheet seems to ignore font + // sizes :( + QTextCharFormat fm = m_tikzEditor->currentCharFormat(); + fm.setFontPointSize(editorFont.pointSize()); + m_tikzEditor->setCurrentCharFormat(fm); + + m_tikzEditor->setTabStopWidth(m_tikzEditor->fontMetrics().width(QLatin1String(" "))); } void TikzEditorView::createActions() { - m_undoAction = StandardAction::undo(m_tikzEditor, SLOT(undo()), this); - m_redoAction = StandardAction::redo(m_tikzEditor, SLOT(redo()), this); - m_cutAction = StandardAction::cut(m_tikzEditor, SLOT(cut()), this); - m_copyAction = StandardAction::copy(m_tikzEditor, SLOT(copy()), this); - m_pasteAction = StandardAction::paste(m_tikzEditor, SLOT(paste()), this); - m_selectAllAction = StandardAction::selectAll(m_tikzEditor, SLOT(selectAll()), this); - m_undoAction->setStatusTip(tr("Undo the previous action")); - m_redoAction->setStatusTip(tr("Redo the previous undone action")); - m_cutAction->setStatusTip(tr("Cut the current selection's contents to the clipboard")); - m_copyAction->setStatusTip(tr("Copy the current selection's contents to the clipboard")); - m_pasteAction->setStatusTip(tr("Paste the clipboard's contents into the current selection")); - m_selectAllAction->setStatusTip(tr("Select all the content")); - m_undoAction->setWhatsThis(tr("

Undo the previous action.

")); - m_redoAction->setWhatsThis(tr("

Redo the previous undone action.

")); - m_cutAction->setWhatsThis(tr("

Cut the current selection's contents to the clipboard.

")); - m_copyAction->setWhatsThis(tr("

Copy the current selection's contents to the clipboard.

")); - m_pasteAction->setWhatsThis(tr("

Paste the clipboard's contents into the current selection.

")); - m_selectAllAction->setWhatsThis(tr("

Select all the content.

")); - - Action *action; - action = new Action(Icon(QLatin1String("format-indent-more")), tr("&Indent..."), this, QLatin1String("edit_indent")); - action->setShortcut(tr("Ctrl+I", "Edit|Indent")); - action->setStatusTip(tr("Indent the current line or selection")); - action->setWhatsThis(tr("

Indent the current line or selection.

")); - connect(action, SIGNAL(triggered()), this, SLOT(editIndent())); - m_editActions.append(action); - - action = new Action(Icon(QLatin1String("format-indent-less")), tr("Unind&ent..."), this, QLatin1String("edit_unindent")); - action->setShortcut(tr("Ctrl+Shift+I", "Edit|Unindent")); - action->setStatusTip(tr("Unindent the current line or selection")); - action->setWhatsThis(tr("

Unindent the current line or selection.

")); - connect(action, SIGNAL(triggered()), this, SLOT(editUnindent())); - m_editActions.append(action); - - action = new Action(tr("C&omment"), this, QLatin1String("edit_comment")); - action->setShortcut(tr("Ctrl+D", "Edit|Comment")); - action->setStatusTip(tr("Comment the current line or selection")); - action->setWhatsThis(tr("

Comment the current line or selection.

")); - connect(action, SIGNAL(triggered()), this, SLOT(editComment())); - m_editActions.append(action); - - action = new Action(tr("Unco&mment"), this, QLatin1String("edit_uncomment")); - action->setShortcut(tr("Ctrl+Shift+D", "Edit|Uncomment")); - action->setStatusTip(tr("Uncomment the current line or selection")); - action->setWhatsThis(tr("

Uncomment the current line or selection.

")); - connect(action, SIGNAL(triggered()), this, SLOT(editUncomment())); - m_editActions.append(action); - - action = new Action(this); - action->setSeparator(true); - m_editActions.append(action); - - m_editActions.append(StandardAction::find(this, SLOT(editFind()), this)); - m_editActions.append(StandardAction::findNext(this, SLOT(editFindNext()), this)); - m_editActions.append(StandardAction::findPrev(this, SLOT(editFindPrevious()), this)); - m_editActions.append(StandardAction::replace(this, SLOT(editReplace()), this)); - m_editActions.append(StandardAction::gotoLine(this, SLOT(editGoToLine()), this)); - m_editActions.at(5)->setStatusTip(tr("Look up a piece of text in the document")); - m_editActions.at(6)->setStatusTip(tr("Search the next occurrence of a text")); - m_editActions.at(7)->setStatusTip(tr("Search the previous occurrence of a text")); - m_editActions.at(8)->setStatusTip(tr("Search and replace a piece of text in the document")); - m_editActions.at(9)->setStatusTip(tr("Go to a certain line in the document")); - m_editActions.at(5)->setWhatsThis(tr("

Look up a piece of text in the document.

")); - m_editActions.at(6)->setWhatsThis(tr("

Search the next occurrence of a text.

")); - m_editActions.at(7)->setWhatsThis(tr("

Search the previous occurrence of a text.

")); - m_editActions.at(8)->setWhatsThis(tr("

Search and replace a piece of text in the document.

")); - m_editActions.at(9)->setWhatsThis(tr("

Go to a certain line in the document.

")); - - m_undoAction->setEnabled(false); - m_redoAction->setEnabled(false); - m_cutAction->setEnabled(false); - m_copyAction->setEnabled(false); - // don't do m_pasteAction->setEnabled(m_tikzEditor->canPaste()); here, because m_tikzEditor->canPaste() is slow if the clipboard contains any text - - connect(m_tikzEditor, SIGNAL(undoAvailable(bool)), - m_undoAction, SLOT(setEnabled(bool))); - connect(m_tikzEditor, SIGNAL(redoAvailable(bool)), - m_redoAction, SLOT(setEnabled(bool))); - connect(m_tikzEditor, SIGNAL(copyAvailable(bool)), - m_cutAction, SLOT(setEnabled(bool))); - connect(m_tikzEditor, SIGNAL(copyAvailable(bool)), - m_copyAction, SLOT(setEnabled(bool))); - connect(QApplication::clipboard(), SIGNAL(dataChanged()), - this, SLOT(setPasteEnabled())); - - m_setBookmarkAction = new Action(Icon(QLatin1String("bookmark-new")), tr("Set &Bookmark"), this, QLatin1String("bookmarks_set")); - m_setBookmarkAction->setShortcut(tr("Ctrl+B", "Bookmarks|Set")); - m_setBookmarkAction->setStatusTip(tr("Set or unset a bookmark at the current line")); - m_setBookmarkAction->setWhatsThis(tr("

Set or unset a bookmark at the current line.

")); - connect(m_setBookmarkAction, SIGNAL(triggered()), m_tikzEditor, SLOT(toggleUserBookmark())); - - m_previousBookmarkAction = new Action(tr("&Previous Bookmark"), this, QLatin1String("bookmarks_prev")); - m_previousBookmarkAction->setShortcut(tr("Alt+Up", "Bookmarks|Previous")); - m_previousBookmarkAction->setStatusTip(tr("Go to the previous bookmark")); - m_previousBookmarkAction->setWhatsThis(tr("

Go to the previous bookmark.

")); - connect(m_previousBookmarkAction, SIGNAL(triggered()), m_tikzEditor, SLOT(previousUserBookmark())); - - m_nextBookmarkAction = new Action(tr("&Next Bookmark"), this, QLatin1String("bookmarks_next")); - m_nextBookmarkAction->setShortcut(tr("Alt+Down", "Bookmarks|Next")); - m_nextBookmarkAction->setStatusTip(tr("Go to the next bookmark")); - m_nextBookmarkAction->setWhatsThis(tr("

Go to the next bookmark.

")); - connect(m_nextBookmarkAction, SIGNAL(triggered()), m_tikzEditor, SLOT(nextUserBookmark())); + m_undoAction = StandardAction::undo(m_tikzEditor, SLOT(undo()), this); + m_redoAction = StandardAction::redo(m_tikzEditor, SLOT(redo()), this); + m_cutAction = StandardAction::cut(m_tikzEditor, SLOT(cut()), this); + m_copyAction = StandardAction::copy(m_tikzEditor, SLOT(copy()), this); + m_pasteAction = StandardAction::paste(m_tikzEditor, SLOT(paste()), this); + m_selectAllAction = StandardAction::selectAll(m_tikzEditor, SLOT(selectAll()), this); + m_undoAction->setStatusTip(tr("Undo the previous action")); + m_redoAction->setStatusTip(tr("Redo the previous undone action")); + m_cutAction->setStatusTip(tr("Cut the current selection's contents to the clipboard")); + m_copyAction->setStatusTip(tr("Copy the current selection's contents to the clipboard")); + m_pasteAction->setStatusTip(tr("Paste the clipboard's contents into the current selection")); + m_selectAllAction->setStatusTip(tr("Select all the content")); + m_undoAction->setWhatsThis(tr("

Undo the previous action.

")); + m_redoAction->setWhatsThis(tr("

Redo the previous undone action.

")); + m_cutAction->setWhatsThis(tr("

Cut the current selection's contents to the clipboard.

")); + m_copyAction->setWhatsThis( + tr("

Copy the current selection's contents to the clipboard.

")); + m_pasteAction->setWhatsThis( + tr("

Paste the clipboard's contents into the current selection.

")); + m_selectAllAction->setWhatsThis(tr("

Select all the content.

")); + + Action *action; + action = new Action(Icon(QLatin1String("format-indent-more")), tr("&Indent..."), this, + QLatin1String("edit_indent")); + action->setShortcut(tr("Ctrl+I", "Edit|Indent")); + action->setStatusTip(tr("Indent the current line or selection")); + action->setWhatsThis(tr("

Indent the current line or selection.

")); + connect(action, SIGNAL(triggered()), this, SLOT(editIndent())); + m_editActions.append(action); + + action = new Action(Icon(QLatin1String("format-indent-less")), tr("Unind&ent..."), this, + QLatin1String("edit_unindent")); + action->setShortcut(tr("Ctrl+Shift+I", "Edit|Unindent")); + action->setStatusTip(tr("Unindent the current line or selection")); + action->setWhatsThis(tr("

Unindent the current line or selection.

")); + connect(action, SIGNAL(triggered()), this, SLOT(editUnindent())); + m_editActions.append(action); + + action = new Action(tr("C&omment"), this, QLatin1String("edit_comment")); + action->setShortcut(tr("Ctrl+D", "Edit|Comment")); + action->setStatusTip(tr("Comment the current line or selection")); + action->setWhatsThis(tr("

Comment the current line or selection.

")); + connect(action, SIGNAL(triggered()), this, SLOT(editComment())); + m_editActions.append(action); + + action = new Action(tr("Unco&mment"), this, QLatin1String("edit_uncomment")); + action->setShortcut(tr("Ctrl+Shift+D", "Edit|Uncomment")); + action->setStatusTip(tr("Uncomment the current line or selection")); + action->setWhatsThis(tr("

Uncomment the current line or selection.

")); + connect(action, SIGNAL(triggered()), this, SLOT(editUncomment())); + m_editActions.append(action); + + action = new Action(this); + action->setSeparator(true); + m_editActions.append(action); + + m_editActions.append(StandardAction::find(this, SLOT(editFind()), this)); + m_editActions.append(StandardAction::findNext(this, SLOT(editFindNext()), this)); + m_editActions.append(StandardAction::findPrev(this, SLOT(editFindPrevious()), this)); + m_editActions.append(StandardAction::replace(this, SLOT(editReplace()), this)); + m_editActions.append(StandardAction::gotoLine(this, SLOT(editGoToLine()), this)); + m_editActions.at(5)->setStatusTip(tr("Look up a piece of text in the document")); + m_editActions.at(6)->setStatusTip(tr("Search the next occurrence of a text")); + m_editActions.at(7)->setStatusTip(tr("Search the previous occurrence of a text")); + m_editActions.at(8)->setStatusTip(tr("Search and replace a piece of text in the document")); + m_editActions.at(9)->setStatusTip(tr("Go to a certain line in the document")); + m_editActions.at(5)->setWhatsThis(tr("

Look up a piece of text in the document.

")); + m_editActions.at(6)->setWhatsThis(tr("

Search the next occurrence of a text.

")); + m_editActions.at(7)->setWhatsThis(tr("

Search the previous occurrence of a text.

")); + m_editActions.at(8)->setWhatsThis( + tr("

Search and replace a piece of text in the document.

")); + m_editActions.at(9)->setWhatsThis(tr("

Go to a certain line in the document.

")); + + m_undoAction->setEnabled(false); + m_redoAction->setEnabled(false); + m_cutAction->setEnabled(false); + m_copyAction->setEnabled(false); + // don't do m_pasteAction->setEnabled(m_tikzEditor->canPaste()); here, because + // m_tikzEditor->canPaste() is slow if the clipboard contains any text + + connect(m_tikzEditor, SIGNAL(undoAvailable(bool)), m_undoAction, SLOT(setEnabled(bool))); + connect(m_tikzEditor, SIGNAL(redoAvailable(bool)), m_redoAction, SLOT(setEnabled(bool))); + connect(m_tikzEditor, SIGNAL(copyAvailable(bool)), m_cutAction, SLOT(setEnabled(bool))); + connect(m_tikzEditor, SIGNAL(copyAvailable(bool)), m_copyAction, SLOT(setEnabled(bool))); + connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(setPasteEnabled())); + + m_setBookmarkAction = new Action(Icon(QLatin1String("bookmark-new")), tr("Set &Bookmark"), this, + QLatin1String("bookmarks_set")); + m_setBookmarkAction->setShortcut(tr("Ctrl+B", "Bookmarks|Set")); + m_setBookmarkAction->setStatusTip(tr("Set or unset a bookmark at the current line")); + m_setBookmarkAction->setWhatsThis(tr("

Set or unset a bookmark at the current line.

")); + connect(m_setBookmarkAction, SIGNAL(triggered()), m_tikzEditor, SLOT(toggleUserBookmark())); + + m_previousBookmarkAction = + new Action(tr("&Previous Bookmark"), this, QLatin1String("bookmarks_prev")); + m_previousBookmarkAction->setShortcut(tr("Alt+Up", "Bookmarks|Previous")); + m_previousBookmarkAction->setStatusTip(tr("Go to the previous bookmark")); + m_previousBookmarkAction->setWhatsThis(tr("

Go to the previous bookmark.

")); + connect(m_previousBookmarkAction, SIGNAL(triggered()), m_tikzEditor, + SLOT(previousUserBookmark())); + + m_nextBookmarkAction = new Action(tr("&Next Bookmark"), this, QLatin1String("bookmarks_next")); + m_nextBookmarkAction->setShortcut(tr("Alt+Down", "Bookmarks|Next")); + m_nextBookmarkAction->setStatusTip(tr("Go to the next bookmark")); + m_nextBookmarkAction->setWhatsThis(tr("

Go to the next bookmark.

")); + connect(m_nextBookmarkAction, SIGNAL(triggered()), m_tikzEditor, SLOT(nextUserBookmark())); } #ifndef KTIKZ_USE_KDE QMenu *TikzEditorView::editMenu() { - QMenu *editMenu = new QMenu(tr("&Edit"), parentWidget()); - editMenu->addAction(m_undoAction); - editMenu->addAction(m_redoAction); - editMenu->addSeparator(); - editMenu->addAction(m_cutAction); - editMenu->addAction(m_copyAction); - editMenu->addAction(m_pasteAction); - editMenu->addSeparator(); - editMenu->addAction(m_selectAllAction); - editMenu->addSeparator(); - editMenu->addActions(m_editActions); - return editMenu; + QMenu *editMenu = new QMenu(tr("&Edit"), parentWidget()); + editMenu->addAction(m_undoAction); + editMenu->addAction(m_redoAction); + editMenu->addSeparator(); + editMenu->addAction(m_cutAction); + editMenu->addAction(m_copyAction); + editMenu->addAction(m_pasteAction); + editMenu->addSeparator(); + editMenu->addAction(m_selectAllAction); + editMenu->addSeparator(); + editMenu->addActions(m_editActions); + return editMenu; } QMenu *TikzEditorView::bookmarksMenu() { - QMenu *bookmarksMenu = new QMenu(tr("&Bookmarks"), parentWidget()); - bookmarksMenu->addAction(m_setBookmarkAction); - bookmarksMenu->addAction(m_previousBookmarkAction); - bookmarksMenu->addAction(m_nextBookmarkAction); - return bookmarksMenu; + QMenu *bookmarksMenu = new QMenu(tr("&Bookmarks"), parentWidget()); + bookmarksMenu->addAction(m_setBookmarkAction); + bookmarksMenu->addAction(m_previousBookmarkAction); + bookmarksMenu->addAction(m_nextBookmarkAction); + return bookmarksMenu; } QToolBar *TikzEditorView::toolBar() { - QToolBar *editToolBar = new QToolBar(tr("Edit"), parentWidget()); - editToolBar->setObjectName(QLatin1String("EditToolBar")); - editToolBar->addAction(m_undoAction); - editToolBar->addAction(m_redoAction); -// editToolBar->addAction(m_cutAction); -// editToolBar->addAction(m_copyAction); -// editToolBar->addAction(m_pasteAction); - return editToolBar; + QToolBar *editToolBar = new QToolBar(tr("Edit"), parentWidget()); + editToolBar->setObjectName(QLatin1String("EditToolBar")); + editToolBar->addAction(m_undoAction); + editToolBar->addAction(m_redoAction); + // editToolBar->addAction(m_cutAction); + // editToolBar->addAction(m_copyAction); + // editToolBar->addAction(m_pasteAction); + return editToolBar; } #endif void TikzEditorView::setPasteEnabled() { - m_pasteAction->setEnabled(m_tikzEditor->canPaste()); + m_pasteAction->setEnabled(m_tikzEditor->canPaste()); } void TikzEditorView::applySettings() { - QSettings settings; - - settings.beginGroup(QLatin1String("Editor")); - // set editor font - m_tikzEditor->setShowLineNumberArea(settings.value(QLatin1String("ShowLineNumberArea"), ConfigEditorWidget::defaultSetting(QLatin1String("ShowLineNumberArea"))).toBool()); - QFont editorFont; - editorFont.fromString(settings.value(QLatin1String("Font"), ConfigEditorWidget::defaultSetting(QLatin1String("Font"))).toString()); - setFont(editorFont); - - // set colors - m_tikzEditor->setShowWhiteSpaces(settings.value(QLatin1String("ShowWhiteSpaces"), ConfigEditorWidget::defaultSetting(QLatin1String("ShowWhiteSpaces"))).toBool()); - m_tikzEditor->setShowTabulators(settings.value(QLatin1String("ShowTabulators"), ConfigEditorWidget::defaultSetting(QLatin1String("ShowTabulators"))).toBool()); - m_tikzEditor->setShowMatchingBrackets(settings.value(QLatin1String("ShowMatchingBrackets"), ConfigEditorWidget::defaultSetting(QLatin1String("ShowMatchingBrackets"))).toBool()); - m_tikzEditor->setWhiteSpacesColor(settings.value(QLatin1String("ColorWhiteSpaces"), ConfigEditorWidget::defaultSetting(QLatin1String("ColorWhiteSpaces"))).value()); - m_tikzEditor->setTabulatorsColor(settings.value(QLatin1String("ColorTabulators"), ConfigEditorWidget::defaultSetting(QLatin1String("ColorTabulators"))).value()); - m_tikzEditor->setMatchingColor(settings.value(QLatin1String("ColorMatchingBrackets"), ConfigEditorWidget::defaultSetting(QLatin1String("ColorMatchingBrackets"))).value()); - m_tikzEditor->setHighlightCurrentLine(settings.value(QLatin1String("ShowHighlightCurrentLine"), ConfigEditorWidget::defaultSetting(QLatin1String("ShowHighlightCurrentLine"))).toBool()); - m_tikzEditor->setHighlightCurrentLineColor(settings.value(QLatin1String("ColorHighlightCurrentLine"), ConfigEditorWidget::defaultSetting(QLatin1String("ColorHighlightCurrentLine"))).value()); - settings.endGroup(); - -/* - tikzHighlighter->applySettings(); - tikzHighlighter->rehighlight(); -*/ + QSettings settings; + + settings.beginGroup(QLatin1String("Editor")); + // set editor font + m_tikzEditor->setShowLineNumberArea( + settings.value(QLatin1String("ShowLineNumberArea"), + ConfigEditorWidget::defaultSetting(QLatin1String("ShowLineNumberArea"))) + .toBool()); + QFont editorFont; + editorFont.fromString(settings.value(QLatin1String("Font"), + ConfigEditorWidget::defaultSetting(QLatin1String("Font"))) + .toString()); + setFont(editorFont); + + // set colors + m_tikzEditor->setShowWhiteSpaces( + settings.value(QLatin1String("ShowWhiteSpaces"), + ConfigEditorWidget::defaultSetting(QLatin1String("ShowWhiteSpaces"))) + .toBool()); + m_tikzEditor->setShowTabulators( + settings.value(QLatin1String("ShowTabulators"), + ConfigEditorWidget::defaultSetting(QLatin1String("ShowTabulators"))) + .toBool()); + m_tikzEditor->setShowMatchingBrackets( + settings.value(QLatin1String("ShowMatchingBrackets"), + ConfigEditorWidget::defaultSetting( + QLatin1String("ShowMatchingBrackets"))) + .toBool()); + m_tikzEditor->setWhiteSpacesColor( + settings.value(QLatin1String("ColorWhiteSpaces"), + ConfigEditorWidget::defaultSetting(QLatin1String("ColorWhiteSpaces"))) + .value()); + m_tikzEditor->setTabulatorsColor( + settings.value(QLatin1String("ColorTabulators"), + ConfigEditorWidget::defaultSetting(QLatin1String("ColorTabulators"))) + .value()); + m_tikzEditor->setMatchingColor(settings.value(QLatin1String("ColorMatchingBrackets"), + ConfigEditorWidget::defaultSetting( + QLatin1String("ColorMatchingBrackets"))) + .value()); + m_tikzEditor->setHighlightCurrentLine( + settings.value(QLatin1String("ShowHighlightCurrentLine"), + ConfigEditorWidget::defaultSetting( + QLatin1String("ShowHighlightCurrentLine"))) + .toBool()); + m_tikzEditor->setHighlightCurrentLineColor( + settings.value(QLatin1String("ColorHighlightCurrentLine"), + ConfigEditorWidget::defaultSetting( + QLatin1String("ColorHighlightCurrentLine"))) + .value()); + settings.endGroup(); + + /* + tikzHighlighter->applySettings(); + tikzHighlighter->rehighlight(); + */ } /***************************************************************************/ @@ -327,8 +379,9 @@ void TikzEditorView::applySettings() /* void TikzEditorView::showCursorPosition() { - QTextCursor cursor = m_tikzEditor->textCursor(); - emit cursorPositionChanged(cursor.blockNumber() + 1, cursor.position() - cursor.block().position() + 1); + QTextCursor cursor = m_tikzEditor->textCursor(); + emit cursorPositionChanged(cursor.blockNumber() + 1, cursor.position() - +cursor.block().position() + 1); } */ @@ -337,420 +390,385 @@ void TikzEditorView::showCursorPosition() void TikzEditorView::initGoToLineWidget() { - m_goToLineWidget = new GoToLineWidget(this); - layout()->addWidget(m_goToLineWidget); + m_goToLineWidget = new GoToLineWidget(this); + layout()->addWidget(m_goToLineWidget); - connect(m_goToLineWidget, SIGNAL(goToLine(int)), - this, SLOT(goToLine(int))); - connect(m_goToLineWidget, SIGNAL(focusEditor()), - m_tikzEditor, SLOT(setFocus())); + connect(m_goToLineWidget, SIGNAL(goToLine(int)), this, SLOT(goToLine(int))); + connect(m_goToLineWidget, SIGNAL(focusEditor()), m_tikzEditor, SLOT(setFocus())); } void TikzEditorView::setLine(const QString &line) { - bool ok; - const int lineNumber = line.toInt(&ok, 10); - if (ok) - setLine(lineNumber); + bool ok; + const int lineNumber = line.toInt(&ok, 10); + if (ok) + setLine(lineNumber); } - void TikzEditorView::setLine(int lineNumber) { - if (m_indentWidget) - m_indentWidget->setVisible(false); - if (m_replaceWidget) - { - m_replaceWidget->setVisible(false); - m_replaceCurrentWidget->setVisible(false); - } - if (!m_goToLineWidget) - initGoToLineWidget(); - m_goToLineWidget->setMaximumValue(m_tikzEditor->numOfLines()); - m_goToLineWidget->setValue(lineNumber); - m_goToLineWidget->setVisible(true); - m_goToLineWidget->setFocus(); + if (m_indentWidget) + m_indentWidget->setVisible(false); + if (m_replaceWidget) { + m_replaceWidget->setVisible(false); + m_replaceCurrentWidget->setVisible(false); + } + if (!m_goToLineWidget) + initGoToLineWidget(); + m_goToLineWidget->setMaximumValue(m_tikzEditor->numOfLines()); + m_goToLineWidget->setValue(lineNumber); + m_goToLineWidget->setVisible(true); + m_goToLineWidget->setFocus(); } void TikzEditorView::goToLine(int lineNumber) { - m_goToLineWidget->setVisible(false); - m_tikzEditor->goToLine(lineNumber); - m_tikzEditor->setFocus(); + m_goToLineWidget->setVisible(false); + m_tikzEditor->goToLine(lineNumber); + m_tikzEditor->setFocus(); } void TikzEditorView::editGoToLine() { - int lineNumber = m_tikzEditor->textCursor().blockNumber() + 1; - if (lineNumber < 1) - lineNumber = 1; - setLine(lineNumber); + int lineNumber = m_tikzEditor->textCursor().blockNumber() + 1; + if (lineNumber < 1) + lineNumber = 1; + setLine(lineNumber); } int TikzEditorView::lineNumber() const { - int lineNumber = m_tikzEditor->textCursor().blockNumber() + 1; - return lineNumber < 1 ? 1 : lineNumber; + int lineNumber = m_tikzEditor->textCursor().blockNumber() + 1; + return lineNumber < 1 ? 1 : lineNumber; } /***************************************************************************/ void TikzEditorView::initIndentWidget() { - m_indentWidget = new IndentWidget(this); - layout()->addWidget(m_indentWidget); + m_indentWidget = new IndentWidget(this); + layout()->addWidget(m_indentWidget); - connect(m_indentWidget, SIGNAL(hidden()), - m_tikzEditor, SLOT(setFocus())); - connect(m_indentWidget, SIGNAL(indent(QChar,int,bool)), - this, SLOT(indent(QChar,int,bool))); + connect(m_indentWidget, SIGNAL(hidden()), m_tikzEditor, SLOT(setFocus())); + connect(m_indentWidget, SIGNAL(indent(QChar, int, bool)), this, SLOT(indent(QChar, int, bool))); } void TikzEditorView::openIndentWidget() { - if (m_replaceWidget) - { - m_replaceWidget->setVisible(false); - m_replaceCurrentWidget->setVisible(false); - } - if (m_goToLineWidget) - m_goToLineWidget->setVisible(false); - if (!m_indentWidget) - initIndentWidget(); - m_indentWidget->setVisible(true); - m_indentWidget->setFocus(); + if (m_replaceWidget) { + m_replaceWidget->setVisible(false); + m_replaceCurrentWidget->setVisible(false); + } + if (m_goToLineWidget) + m_goToLineWidget->setVisible(false); + if (!m_indentWidget) + initIndentWidget(); + m_indentWidget->setVisible(true); + m_indentWidget->setFocus(); } void TikzEditorView::editIndent() { - openIndentWidget(); - m_indentWidget->setUnindenting(false); + openIndentWidget(); + m_indentWidget->setUnindenting(false); } void TikzEditorView::editUnindent() { - openIndentWidget(); - m_indentWidget->setUnindenting(true); + openIndentWidget(); + m_indentWidget->setUnindenting(true); } void TikzEditorView::tabIndent(bool isUnindenting) { - if (!m_indentWidget) // make sure m_indentWidget exists before we use its members - initIndentWidget(); - indent(m_indentWidget->insertChar(), m_indentWidget->numOfInserts(), isUnindenting); + if (!m_indentWidget) // make sure m_indentWidget exists before we use its members + initIndentWidget(); + indent(m_indentWidget->insertChar(), m_indentWidget->numOfInserts(), isUnindenting); } void TikzEditorView::indent(QChar insertChar, int numOfInserts, bool isUnindenting) { - m_indentWidget->setVisible(false); - - QTextCursor textCursor = m_tikzEditor->textCursor(); - if (textCursor.hasSelection()) - { - textCursor.beginEditBlock(); - const int start = textCursor.selectionStart(); - int end = textCursor.selectionEnd(); - textCursor.setPosition(start, QTextCursor::MoveAnchor); - textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - if (!isUnindenting) - { - bool go = true; - while (textCursor.position() < end && go) - { - for (int i = 0; i < numOfInserts; ++i) - { - textCursor.insertText(insertChar); - ++end; // when a character is inserted, textCursor.selectionEnd() is shifted by 1 character, in order to let the test in the while-loop behave correctly, we must increment end - } - go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); - } - } - else - { - bool go = true; - while (textCursor.position() < end && go) - { - for (int i = 0; i < numOfInserts; ++i) - { - if (textCursor.atBlockEnd()) // when the line is empty go to the next line instead of selecting the newline character (possibly together with characters of the next line) - break; - textCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); - if (textCursor.selectedText() == insertChar) - { - textCursor.removeSelectedText(); - --end; // when a character is removed, textCursor.selectionEnd() is shifted by 1 character, in order to let the test in the while-loop behave correctly, we must decrement end - } - } - go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); - } - } - textCursor.endEditBlock(); - } - else - { - textCursor.beginEditBlock(); - textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - if (!isUnindenting) - { - for (int i = 0; i < numOfInserts; ++i) - textCursor.insertText(insertChar); - } - else - { - for (int i = 0; i < numOfInserts; ++i) - { - textCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); - if (textCursor.selectedText() == insertChar) - textCursor.removeSelectedText(); - } - } - textCursor.endEditBlock(); - } - m_tikzEditor->setFocus(); + m_indentWidget->setVisible(false); + + QTextCursor textCursor = m_tikzEditor->textCursor(); + if (textCursor.hasSelection()) { + textCursor.beginEditBlock(); + const int start = textCursor.selectionStart(); + int end = textCursor.selectionEnd(); + textCursor.setPosition(start, QTextCursor::MoveAnchor); + textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + if (!isUnindenting) { + bool go = true; + while (textCursor.position() < end && go) { + for (int i = 0; i < numOfInserts; ++i) { + textCursor.insertText(insertChar); + ++end; // when a character is inserted, textCursor.selectionEnd() is shifted by + // 1 character, in order to let the test in the while-loop behave + // correctly, we must increment end + } + go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); + } + } else { + bool go = true; + while (textCursor.position() < end && go) { + for (int i = 0; i < numOfInserts; ++i) { + if (textCursor + .atBlockEnd()) // when the line is empty go to the next line instead + // of selecting the newline character (possibly + // together with characters of the next line) + break; + textCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); + if (textCursor.selectedText() == insertChar) { + textCursor.removeSelectedText(); + --end; // when a character is removed, textCursor.selectionEnd() is shifted + // by 1 character, in order to let the test in the while-loop behave + // correctly, we must decrement end + } + } + go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); + } + } + textCursor.endEditBlock(); + } else { + textCursor.beginEditBlock(); + textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + if (!isUnindenting) { + for (int i = 0; i < numOfInserts; ++i) + textCursor.insertText(insertChar); + } else { + for (int i = 0; i < numOfInserts; ++i) { + textCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); + if (textCursor.selectedText() == insertChar) + textCursor.removeSelectedText(); + } + } + textCursor.endEditBlock(); + } + m_tikzEditor->setFocus(); } /***************************************************************************/ void TikzEditorView::editComment() { - QTextCursor textCursor = m_tikzEditor->textCursor(); - if (textCursor.hasSelection()) - { - textCursor.beginEditBlock(); - const int start = textCursor.selectionStart(); - int end = textCursor.selectionEnd(); - textCursor.setPosition(start, QTextCursor::MoveAnchor); - textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - bool go = true; - while (textCursor.position() < end && go) - { - textCursor.insertText(QLatin1String("% ")); - ++end; - ++end; - go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); - } - textCursor.endEditBlock(); - } - else - { - textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - textCursor.insertText(QLatin1String("% ")); - } + QTextCursor textCursor = m_tikzEditor->textCursor(); + if (textCursor.hasSelection()) { + textCursor.beginEditBlock(); + const int start = textCursor.selectionStart(); + int end = textCursor.selectionEnd(); + textCursor.setPosition(start, QTextCursor::MoveAnchor); + textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + bool go = true; + while (textCursor.position() < end && go) { + textCursor.insertText(QLatin1String("% ")); + ++end; + ++end; + go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); + } + textCursor.endEditBlock(); + } else { + textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + textCursor.insertText(QLatin1String("% ")); + } } void TikzEditorView::editUncomment() { - QTextCursor textCursor = m_tikzEditor->textCursor(); - if (textCursor.hasSelection()) - { - textCursor.beginEditBlock(); - const int start = textCursor.selectionStart(); - int end = textCursor.selectionEnd() - 2; - textCursor.setPosition(start, QTextCursor::MoveAnchor); - textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - bool go = true; - while (textCursor.position() < end && go) - { - textCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 2); - if (textCursor.selectedText() == QLatin1String("% ")) - { - textCursor.removeSelectedText(); - --end; - } - go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); - } - textCursor.endEditBlock(); - } - else - { - textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); - textCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 2); - if (textCursor.selectedText() == QLatin1String("% ")) - textCursor.removeSelectedText(); - } + QTextCursor textCursor = m_tikzEditor->textCursor(); + if (textCursor.hasSelection()) { + textCursor.beginEditBlock(); + const int start = textCursor.selectionStart(); + int end = textCursor.selectionEnd() - 2; + textCursor.setPosition(start, QTextCursor::MoveAnchor); + textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + bool go = true; + while (textCursor.position() < end && go) { + textCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 2); + if (textCursor.selectedText() == QLatin1String("% ")) { + textCursor.removeSelectedText(); + --end; + } + go = textCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor); + } + textCursor.endEditBlock(); + } else { + textCursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor); + textCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 2); + if (textCursor.selectedText() == QLatin1String("% ")) + textCursor.removeSelectedText(); + } } /***************************************************************************/ void TikzEditorView::initReplaceWidgets() { - m_replaceWidget = new ReplaceWidget(this); - m_replaceCurrentWidget = new ReplaceCurrentWidget(this); - m_replaceCurrentWidget->setVisible(false); + m_replaceWidget = new ReplaceWidget(this); + m_replaceCurrentWidget = new ReplaceCurrentWidget(this); + m_replaceCurrentWidget->setVisible(false); - layout()->addWidget(m_replaceWidget); - layout()->addWidget(m_replaceCurrentWidget); + layout()->addWidget(m_replaceWidget); + layout()->addWidget(m_replaceCurrentWidget); - connect(m_replaceWidget, SIGNAL(search(QString,QTextDocument::FindFlags)), - this, SLOT(search(QString,QTextDocument::FindFlags))); - connect(m_replaceWidget, SIGNAL(replace(QString,QString,QTextDocument::FindFlags)), - this, SLOT(replace(QString,QString,QTextDocument::FindFlags))); - connect(m_replaceWidget, SIGNAL(focusEditor()), - m_tikzEditor, SLOT(setFocus())); + connect(m_replaceWidget, SIGNAL(search(QString, QTextDocument::FindFlags)), this, + SLOT(search(QString, QTextDocument::FindFlags))); + connect(m_replaceWidget, SIGNAL(replace(QString, QString, QTextDocument::FindFlags)), this, + SLOT(replace(QString, QString, QTextDocument::FindFlags))); + connect(m_replaceWidget, SIGNAL(focusEditor()), m_tikzEditor, SLOT(setFocus())); - connect(m_replaceCurrentWidget, SIGNAL(hidden()), - m_tikzEditor, SLOT(setFocus())); - connect(m_replaceCurrentWidget, SIGNAL(search()), - this, SLOT(search())); - connect(m_replaceCurrentWidget, SIGNAL(replace()), - this, SLOT(replace())); - connect(m_replaceCurrentWidget, SIGNAL(replaceAll()), - this, SLOT(replaceAll())); + connect(m_replaceCurrentWidget, SIGNAL(hidden()), m_tikzEditor, SLOT(setFocus())); + connect(m_replaceCurrentWidget, SIGNAL(search()), this, SLOT(search())); + connect(m_replaceCurrentWidget, SIGNAL(replace()), this, SLOT(replace())); + connect(m_replaceCurrentWidget, SIGNAL(replaceAll()), this, SLOT(replaceAll())); } void TikzEditorView::openReplaceWidget() { - if (m_goToLineWidget) - m_goToLineWidget->setVisible(false); - if (m_indentWidget) - m_indentWidget->setVisible(false); - if (!m_replaceWidget) - initReplaceWidgets(); - m_replaceCurrentWidget->setVisible(false); - m_replaceWidget->setVisible(true); - m_replaceWidget->setFocus(); + if (m_goToLineWidget) + m_goToLineWidget->setVisible(false); + if (m_indentWidget) + m_indentWidget->setVisible(false); + if (!m_replaceWidget) + initReplaceWidgets(); + m_replaceCurrentWidget->setVisible(false); + m_replaceWidget->setVisible(true); + m_replaceWidget->setFocus(); } void TikzEditorView::editFind() { - openReplaceWidget(); - const QTextCursor textCursor = m_tikzEditor->textCursor(); - if (textCursor.hasSelection()) - m_replaceWidget->setText(textCursor.selectedText()); -} - -bool TikzEditorView::search(const QString &text, QTextDocument::FindFlags flags, bool startAtCursor, bool continueFromBeginning) -{ - bool isFound = false; - - QTextCursor textCursor = m_tikzEditor->textCursor(); - if (!startAtCursor) - { - if (!(flags & QTextDocument::FindBackward)) - textCursor.movePosition(QTextCursor::Start); - else - textCursor.movePosition(QTextCursor::End); - m_tikzEditor->setTextCursor(textCursor); - } - else - textCursor.setPosition(textCursor.selectionStart()); - if (!(flags & QTextDocument::FindBackward) && !continueFromBeginning) - textCursor.movePosition(QTextCursor::Right); - const QTextCursor found = m_tikzEditor->document()->find(text, textCursor, flags); - - if (found.isNull()) - { - const QString msg = !(flags & QTextDocument::FindBackward) ? - tr("End of document reached.\n\nContinue from the beginning?") - : tr("Beginning of document reached.\n\nContinue from the end?"); - const int result = MessageBox::questionYesNo(this, msg, tr("Find"), tr("Continue")); - if (result == MessageBox::Yes) - return search(text, flags, /*startAtCursor*/ false, /*continueFromBeginning*/ true); - else - { - m_replaceWidget->setVisible(false); - m_replaceCurrentWidget->setVisible(false); - m_tikzEditor->setFocus(); - } - } - else - { - m_tikzEditor->setTextCursor(found); - isFound = true; - } - m_tikzEditor->viewport()->repaint(); - return isFound; + openReplaceWidget(); + const QTextCursor textCursor = m_tikzEditor->textCursor(); + if (textCursor.hasSelection()) + m_replaceWidget->setText(textCursor.selectedText()); +} + +bool TikzEditorView::search(const QString &text, QTextDocument::FindFlags flags, bool startAtCursor, + bool continueFromBeginning) +{ + bool isFound = false; + + QTextCursor textCursor = m_tikzEditor->textCursor(); + if (!startAtCursor) { + if (!(flags & QTextDocument::FindBackward)) + textCursor.movePosition(QTextCursor::Start); + else + textCursor.movePosition(QTextCursor::End); + m_tikzEditor->setTextCursor(textCursor); + } else + textCursor.setPosition(textCursor.selectionStart()); + if (!(flags & QTextDocument::FindBackward) && !continueFromBeginning) + textCursor.movePosition(QTextCursor::Right); + const QTextCursor found = m_tikzEditor->document()->find(text, textCursor, flags); + + if (found.isNull()) { + const QString msg = !(flags & QTextDocument::FindBackward) + ? tr("End of document reached.\n\nContinue from the beginning?") + : tr("Beginning of document reached.\n\nContinue from the end?"); + const int result = MessageBox::questionYesNo(this, msg, tr("Find"), tr("Continue")); + if (result == MessageBox::Yes) + return search(text, flags, /*startAtCursor*/ false, /*continueFromBeginning*/ true); + else { + m_replaceWidget->setVisible(false); + m_replaceCurrentWidget->setVisible(false); + m_tikzEditor->setFocus(); + } + } else { + m_tikzEditor->setTextCursor(found); + isFound = true; + } + m_tikzEditor->viewport()->repaint(); + return isFound; } void TikzEditorView::search() { - search(m_searchText, m_flags, m_startAtCursor); + search(m_searchText, m_flags, m_startAtCursor); } void TikzEditorView::editFindNext() { - openReplaceWidget(); - m_replaceWidget->setForward(true); - m_replaceWidget->doFind(); + openReplaceWidget(); + m_replaceWidget->setForward(true); + m_replaceWidget->doFind(); } void TikzEditorView::editFindPrevious() { - openReplaceWidget(); - m_replaceWidget->setForward(false); - m_replaceWidget->doFind(); + openReplaceWidget(); + m_replaceWidget->setForward(false); + m_replaceWidget->doFind(); } void TikzEditorView::editReplace() { - editFind(); + editFind(); } void TikzEditorView::replace(const QString &replacement) { - QTextCursor textCursor = m_tikzEditor->textCursor(); + QTextCursor textCursor = m_tikzEditor->textCursor(); - if (textCursor.hasSelection()) - { - const int start = textCursor.selectionStart(); - textCursor.beginEditBlock(); - textCursor.removeSelectedText(); - textCursor.insertText(replacement); - textCursor.setPosition(start, QTextCursor::MoveAnchor); - textCursor.setPosition(start + replacement.length(), QTextCursor::KeepAnchor); - textCursor.endEditBlock(); - m_tikzEditor->setTextCursor(textCursor); - } + if (textCursor.hasSelection()) { + const int start = textCursor.selectionStart(); + textCursor.beginEditBlock(); + textCursor.removeSelectedText(); + textCursor.insertText(replacement); + textCursor.setPosition(start, QTextCursor::MoveAnchor); + textCursor.setPosition(start + replacement.length(), QTextCursor::KeepAnchor); + textCursor.endEditBlock(); + m_tikzEditor->setTextCursor(textCursor); + } } -void TikzEditorView::replace(const QString &text, const QString &replacement, QTextDocument::FindFlags flags, bool startAtCursor) +void TikzEditorView::replace(const QString &text, const QString &replacement, + QTextDocument::FindFlags flags, bool startAtCursor) { - m_searchText = text; - m_replaceText = replacement; - m_flags = flags; - m_startAtCursor = startAtCursor; + m_searchText = text; + m_replaceText = replacement; + m_flags = flags; + m_startAtCursor = startAtCursor; - m_replaceWidget->setVisible(false); - m_replaceCurrentWidget->setReplacement(text, replacement); - m_replaceCurrentWidget->setVisible(true); - search(text, flags, startAtCursor); + m_replaceWidget->setVisible(false); + m_replaceCurrentWidget->setReplacement(text, replacement); + m_replaceCurrentWidget->setVisible(true); + search(text, flags, startAtCursor); } void TikzEditorView::replace() { - replace(m_replaceText); - search(m_searchText, m_flags, m_startAtCursor); + replace(m_replaceText); + search(m_searchText, m_flags, m_startAtCursor); } void TikzEditorView::replaceAll() { - replace(m_replaceText); - while (search(m_searchText, m_flags, m_startAtCursor)) - replace(m_replaceText); + replace(m_replaceText); + while (search(m_searchText, m_flags, m_startAtCursor)) + replace(m_replaceText); } void TikzEditorView::updateCompleter(bool useCompletion, const QStringList &words) { - m_tikzEditor->updateCompleter(useCompletion, words); + m_tikzEditor->updateCompleter(useCompletion, words); } void TikzEditorView::clear() { - editor()->clear(); + editor()->clear(); } bool TikzEditorView::isEmpty() { - return document()->isEmpty(); + return document()->isEmpty(); } bool TikzEditorView::isModified() { - return document()->isModified(); + return document()->isModified(); } -void TikzEditorView::setModified( bool value ) +void TikzEditorView::setModified(bool value) { - return document()->setModified( value ); + return document()->setModified(value); } - diff --git a/app/tikzeditorview.h b/app/tikzeditorview.h index 059d883..a6132de 100644 --- a/app/tikzeditorview.h +++ b/app/tikzeditorview.h @@ -26,7 +26,7 @@ class QAction; class QMenu; -//class QSyntaxHighlighter; +// class QSyntaxHighlighter; class QPlainTextEdit; class QToolBar; class Action; @@ -35,103 +35,105 @@ class IndentWidget; class ReplaceWidget; class ReplaceCurrentWidget; class TikzEditor; -//class TikzHighlighter; +// class TikzHighlighter; class TikzEditorView : public TikzEditorViewAbstract { - Q_OBJECT + Q_OBJECT public: - explicit TikzEditorView(QWidget *parent = 0); - virtual ~TikzEditorView(); + explicit TikzEditorView(QWidget *parent = 0); + virtual ~TikzEditorView(); - QPlainTextEdit *editor(); - QTextDocument *document(); - QString text(); + QPlainTextEdit *editor(); + QTextDocument *document(); + QString text(); #ifndef KTIKZ_USE_KDE - QMenu *editMenu(); - QMenu *bookmarksMenu(); - QToolBar *toolBar(); + QMenu *editMenu(); + QMenu *bookmarksMenu(); + QToolBar *toolBar(); #endif - void applySettings(); - void setLine(const QString &line); - int lineNumber() const; - void updateCompleter(bool useCompletion, const QStringList &words); - void clear(); - bool isEmpty(); - bool isModified(); - void setModified( bool value ); + void applySettings(); + void setLine(const QString &line); + int lineNumber() const; + void updateCompleter(bool useCompletion, const QStringList &words); + void clear(); + bool isEmpty(); + bool isModified(); + void setModified(bool value); public Q_SLOTS: - void setPasteEnabled(); - void goToLine(int lineNumber); + void setPasteEnabled(); + void goToLine(int lineNumber); Q_SIGNALS: - void modificationChanged(bool changed); - void contentsChanged(); - void cursorPositionChanged(int row, int col); - void showStatusMessage(const QString &message, int timeout = 3000); - void setSearchFromBegin(bool searchFromBegin); - void focusIn(); - void focusOut(); + void modificationChanged(bool changed); + void contentsChanged(); + void cursorPositionChanged(int row, int col); + void showStatusMessage(const QString &message, int timeout = 3000); + void setSearchFromBegin(bool searchFromBegin); + void focusIn(); + void focusOut(); private Q_SLOTS: -// void showCursorPosition(); - void editGoToLine(); - void editIndent(); - void editUnindent(); - void editComment(); - void editUncomment(); - void editFind(); - void editFindNext(); - void editFindPrevious(); - void editReplace(); - void tabIndent(bool isUnindenting = false); - void indent(QChar insertChar, int numOfInserts, bool isUnindenting = false); - bool search(const QString &text, QTextDocument::FindFlags flags = 0, bool startAtCursor = true, bool continueFromBeginning = false); - void search(); - void replace(const QString &replacement); - void replace(const QString &text, const QString &replacement, QTextDocument::FindFlags flags = 0, bool startAtCursor = true); - void replace(); - void replaceAll(); + // void showCursorPosition(); + void editGoToLine(); + void editIndent(); + void editUnindent(); + void editComment(); + void editUncomment(); + void editFind(); + void editFindNext(); + void editFindPrevious(); + void editReplace(); + void tabIndent(bool isUnindenting = false); + void indent(QChar insertChar, int numOfInserts, bool isUnindenting = false); + bool search(const QString &text, QTextDocument::FindFlags flags = 0, bool startAtCursor = true, + bool continueFromBeginning = false); + void search(); + void replace(const QString &replacement); + void replace(const QString &text, const QString &replacement, + QTextDocument::FindFlags flags = 0, bool startAtCursor = true); + void replace(); + void replaceAll(); private: - void setFont(const QFont &editorFont); - void createActions(); - void initGoToLineWidget(); - void setLine(int lineNumber); - void initIndentWidget(); - void openIndentWidget(); - void initReplaceWidgets(); - void openReplaceWidget(); - - TikzEditor *m_tikzEditor; - GoToLineWidget *m_goToLineWidget; - IndentWidget *m_indentWidget; - ReplaceWidget *m_replaceWidget; - ReplaceCurrentWidget *m_replaceCurrentWidget; - - QString m_searchText; - QString m_replaceText; - QTextDocument::FindFlags m_flags; - bool m_startAtCursor; - -// TikzHighlighter *tikzHighlighter; - -// TikzCommandInserter *commandInserter; - - QAction *m_undoAction; - QAction *m_redoAction; - QAction *m_cutAction; - QAction *m_copyAction; - QAction *m_pasteAction; - QAction *m_selectAllAction; - QList m_editActions; - Action *m_setBookmarkAction; - Action *m_previousBookmarkAction; - Action *m_nextBookmarkAction; - -// int customHighlighting; + void setFont(const QFont &editorFont); + void createActions(); + void initGoToLineWidget(); + void setLine(int lineNumber); + void initIndentWidget(); + void openIndentWidget(); + void initReplaceWidgets(); + void openReplaceWidget(); + + TikzEditor *m_tikzEditor; + GoToLineWidget *m_goToLineWidget; + IndentWidget *m_indentWidget; + ReplaceWidget *m_replaceWidget; + ReplaceCurrentWidget *m_replaceCurrentWidget; + + QString m_searchText; + QString m_replaceText; + QTextDocument::FindFlags m_flags; + bool m_startAtCursor; + + // TikzHighlighter *tikzHighlighter; + + // TikzCommandInserter *commandInserter; + + QAction *m_undoAction; + QAction *m_redoAction; + QAction *m_cutAction; + QAction *m_copyAction; + QAction *m_pasteAction; + QAction *m_selectAllAction; + QList m_editActions; + Action *m_setBookmarkAction; + Action *m_previousBookmarkAction; + Action *m_nextBookmarkAction; + + // int customHighlighting; }; #endif diff --git a/app/tikzeditorviewabstract.h b/app/tikzeditorviewabstract.h index cdf667e..5209c69 100644 --- a/app/tikzeditorviewabstract.h +++ b/app/tikzeditorviewabstract.h @@ -21,17 +21,15 @@ #include #ifndef KTIKZ_USE_KDE -#include -#include +# include +# include #endif -class TikzEditorViewAbstract: public QWidget +class TikzEditorViewAbstract : public QWidget { public: - explicit TikzEditorViewAbstract(QWidget *parent = 0) - : QWidget(parent) - {} - virtual ~TikzEditorViewAbstract() { }; + explicit TikzEditorViewAbstract(QWidget *parent = 0) : QWidget(parent) { } + virtual ~TikzEditorViewAbstract(){}; #ifndef KTIKZ_USE_KDE virtual QMenu *editMenu() = 0; @@ -44,7 +42,6 @@ class TikzEditorViewAbstract: public QWidget virtual bool isEmpty() = 0; virtual bool isModified() = 0; virtual void setModified(bool value) = 0; - }; #endif diff --git a/app/tikzktexteditorcompletion.cpp b/app/tikzktexteditorcompletion.cpp index e71381b..050e338 100644 --- a/app/tikzktexteditorcompletion.cpp +++ b/app/tikzktexteditorcompletion.cpp @@ -29,43 +29,36 @@ #include #include - -TikzKTextEditorCompletion::TikzKTextEditorCompletion(QObject* parent) - : KTextEditor::CodeCompletionModel(parent) +TikzKTextEditorCompletion::TikzKTextEditorCompletion(QObject *parent) + : KTextEditor::CodeCompletionModel(parent) { - m_wordsList.clear(); + m_wordsList.clear(); } -TikzKTextEditorCompletion::~TikzKTextEditorCompletion() -{ - - -} +TikzKTextEditorCompletion::~TikzKTextEditorCompletion() { } void TikzKTextEditorCompletion::updateCompleter(bool useCompletion, const QStringList &words) { - m_useCompletion = useCompletion; - m_wordsList = words; - findMatches(); + m_useCompletion = useCompletion; + m_wordsList = words; + findMatches(); } void TikzKTextEditorCompletion::findMatches() { - m_matches.clear(); - for( int i = 0; i < m_wordsList.size(); i++ ) - { - QStandardItem* item = new QStandardItem(); - item->setData( m_wordsList.at(i) , Qt::DisplayRole); - if( m_wordsList.at(i).startsWith(QStringLiteral("\\")) ) - { - item->setData(QIcon::fromTheme(QStringLiteral("code-function")), Qt::DecorationRole); - } - m_matches.appendRow( item ); - } + m_matches.clear(); + for (int i = 0; i < m_wordsList.size(); i++) { + QStandardItem *item = new QStandardItem(); + item->setData(m_wordsList.at(i), Qt::DisplayRole); + if (m_wordsList.at(i).startsWith(QStringLiteral("\\"))) { + item->setData(QIcon::fromTheme(QStringLiteral("code-function")), Qt::DecorationRole); + } + m_matches.appendRow(item); + } } - -//bool TikzKTextEditorCompletion::shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, bool userInsertion, const KTextEditor::Cursor &position) +// bool TikzKTextEditorCompletion::shouldStartCompletion(KTextEditor::View *view, const QString +// &insertedText, bool userInsertion, const KTextEditor::Cursor &position) //{ // if( !m_useCompletion ) // return false; @@ -81,69 +74,62 @@ void TikzKTextEditorCompletion::findMatches() // return true; // } // return false; -//} - +// } -KTextEditor::Range TikzKTextEditorCompletion::completionRange(KTextEditor::View *view, const KTextEditor::Cursor &position) +KTextEditor::Range TikzKTextEditorCompletion::completionRange(KTextEditor::View *view, + const KTextEditor::Cursor &position) { - KTextEditor::Range range = view->document()->wordRangeAt( position ); - return range; + KTextEditor::Range range = view->document()->wordRangeAt(position); + return range; } -void TikzKTextEditorCompletion::completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, KTextEditor::CodeCompletionModel::InvocationType it) +void TikzKTextEditorCompletion::completionInvoked( + KTextEditor::View *view, const KTextEditor::Range &range, + KTextEditor::CodeCompletionModel::InvocationType it) { - setRowCount(m_matches.rowCount()); + setRowCount(m_matches.rowCount()); } QVariant TikzKTextEditorCompletion::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() >= m_matches.rowCount()) { - return QVariant(); - } - - const QStandardItem *match = m_matches.item(index.row()); - - if(index.column() == KTextEditor::CodeCompletionModel::Name && role == Qt::DisplayRole) - { - QString name = match->data( Qt::DisplayRole ).toString(); - return name; - } - if(index.column() == KTextEditor::CodeCompletionModel::Icon && role == Qt::DecorationRole) - { - return match->data( Qt::DecorationRole ); - } - - switch (role) - { - case KTextEditor::CodeCompletionModel::CompletionRole: - { - int p = KTextEditor::CodeCompletionModel::NoProperty; - return p; - } - case KTextEditor::CodeCompletionModel::BestMatchesCount: - { - return 1; - } - case KTextEditor::CodeCompletionModel::ArgumentHintDepth: - { - return 0; - } - case KTextEditor::CodeCompletionModel::GroupRole: - { - break; - } - case KTextEditor::CodeCompletionModel::IsExpandable: - { - // I like the green arrow - return false; - } - case KTextEditor::CodeCompletionModel::ExpandingWidget: - { - // TODO well implementation in DCD is missing - break; - } - } - - return QVariant(); + if (!index.isValid() || index.row() >= m_matches.rowCount()) { + return QVariant(); + } + + const QStandardItem *match = m_matches.item(index.row()); + + if (index.column() == KTextEditor::CodeCompletionModel::Name && role == Qt::DisplayRole) { + QString name = match->data(Qt::DisplayRole).toString(); + return name; + } + if (index.column() == KTextEditor::CodeCompletionModel::Icon && role == Qt::DecorationRole) { + return match->data(Qt::DecorationRole); + } + + switch (role) { + case KTextEditor::CodeCompletionModel::CompletionRole: { + int p = KTextEditor::CodeCompletionModel::NoProperty; + return p; + } + case KTextEditor::CodeCompletionModel::BestMatchesCount: { + return 1; + } + case KTextEditor::CodeCompletionModel::ArgumentHintDepth: { + return 0; + } + case KTextEditor::CodeCompletionModel::GroupRole: { + break; + } + case KTextEditor::CodeCompletionModel::IsExpandable: { + // I like the green arrow + return false; + } + case KTextEditor::CodeCompletionModel::ExpandingWidget: { + // TODO well implementation in DCD is missing + break; + } + } + + return QVariant(); } diff --git a/app/tikzktexteditorcompletion.h b/app/tikzktexteditorcompletion.h index 6865fa5..39213f9 100644 --- a/app/tikzktexteditorcompletion.h +++ b/app/tikzktexteditorcompletion.h @@ -30,48 +30,48 @@ #include namespace KTextEditor { - class Document; - class View; -} +class Document; +class View; +} // namespace KTextEditor - -class TikzKTextEditorCompletion - : public KTextEditor::CodeCompletionModel - , public KTextEditor::CodeCompletionModelControllerInterface +class TikzKTextEditorCompletion : public KTextEditor::CodeCompletionModel, + public KTextEditor::CodeCompletionModelControllerInterface { - Q_OBJECT + Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) + Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: - TikzKTextEditorCompletion(QObject* parent); - ~TikzKTextEditorCompletion(); + TikzKTextEditorCompletion(QObject *parent); + ~TikzKTextEditorCompletion(); - void updateCompleter(bool useCompletion, const QStringList &words); + void updateCompleter(bool useCompletion, const QStringList &words); - //bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, bool userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - KTextEditor::Range completionRange(KTextEditor::View *view, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - //QString filterString(KTextEditor::View *view, const KTextEditor::Range &range, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + // bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, bool + // userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + KTextEditor::Range completionRange(KTextEditor::View *view, + const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + // QString filterString(KTextEditor::View *view, const KTextEditor::Range &range, const + // KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, KTextEditor::CodeCompletionModel::InvocationType it) Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; + void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, + KTextEditor::CodeCompletionModel::InvocationType it) Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; private: - - void findMatches(); - - bool m_useCompletion; - QStringList m_wordsList; - /** - * model with matching data - */ - QStandardItemModel m_matches; - - /** - * automatic invocation? - */ - bool m_automatic; + void findMatches(); + + bool m_useCompletion; + QStringList m_wordsList; + /** + * model with matching data + */ + QStandardItemModel m_matches; + + /** + * automatic invocation? + */ + bool m_automatic; }; #endif - diff --git a/app/tikzktexteditorview.cpp b/app/tikzktexteditorview.cpp index 3f7c0d5..d3dd88c 100644 --- a/app/tikzktexteditorview.cpp +++ b/app/tikzktexteditorview.cpp @@ -28,96 +28,88 @@ #include #include -TikzKTextEditorView::TikzKTextEditorView(QWidget *parent) - : TikzEditorViewAbstract(parent) +TikzKTextEditorView::TikzKTextEditorView(QWidget *parent) : TikzEditorViewAbstract(parent) { - m_currentDoc = KTextEditor::Editor::instance()->createDocument(this); - // create a widget to display the document - m_documentView = m_currentDoc->createView(this); + m_currentDoc = KTextEditor::Editor::instance()->createDocument(this); + // create a widget to display the document + m_documentView = m_currentDoc->createView(this); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setMargin(0); - mainLayout->addWidget(m_documentView); + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setMargin(0); + mainLayout->addWidget(m_documentView); - m_currentDoc->setMode(QStringLiteral("LaTeX")); + m_currentDoc->setMode(QStringLiteral("LaTeX")); + connect(m_currentDoc, SIGNAL(modifiedChanged(KTextEditor::Document *)), this, + SLOT(setDocumentModified(KTextEditor::Document *))); - connect(m_currentDoc, SIGNAL(modifiedChanged(KTextEditor::Document*)), - this, SLOT(setDocumentModified(KTextEditor::Document*))); + connect(m_documentView, SIGNAL(focusIn(KTextEditor::View *)), this, SIGNAL(focusIn())); + connect(m_documentView, SIGNAL(focusOut(KTextEditor::View *)), this, SIGNAL(focusOut())); - connect(m_documentView, SIGNAL(focusIn(KTextEditor::View*)), - this, SIGNAL(focusIn())); - connect(m_documentView, SIGNAL(focusOut(KTextEditor::View*)), - this, SIGNAL(focusOut())); + connect(m_currentDoc, SIGNAL(textChanged(KTextEditor::Document *)), this, + SIGNAL(contentsChanged())); - connect(m_currentDoc, SIGNAL(textChanged(KTextEditor::Document*)), - this, SIGNAL(contentsChanged())); - - connect(m_currentDoc, SIGNAL(urlChanged(const QUrl&)), - this, SIGNAL(documentUrlChanged(const QUrl&))); - - KTextEditor::CodeCompletionInterface *cci = qobject_cast(m_documentView); - if (cci) { - m_completion = new TikzKTextEditorCompletion(this); - cci->registerCompletionModel(m_completion); - } - -} - -TikzKTextEditorView::~TikzKTextEditorView() -{ + connect(m_currentDoc, SIGNAL(urlChanged(const QUrl &)), this, + SIGNAL(documentUrlChanged(const QUrl &))); + KTextEditor::CodeCompletionInterface *cci = + qobject_cast(m_documentView); + if (cci) { + m_completion = new TikzKTextEditorCompletion(this); + cci->registerCompletionModel(m_completion); + } } +TikzKTextEditorView::~TikzKTextEditorView() { } -KTextEditor::Document* TikzKTextEditorView::editor() +KTextEditor::Document *TikzKTextEditorView::editor() { - return document(); + return document(); } -KTextEditor::Document* TikzKTextEditorView::document() +KTextEditor::Document *TikzKTextEditorView::document() { - return m_currentDoc; + return m_currentDoc; } QString TikzKTextEditorView::text() { - return m_currentDoc->text(); + return m_currentDoc->text(); } -KTextEditor::View* TikzKTextEditorView::view() +KTextEditor::View *TikzKTextEditorView::view() { - return m_documentView; + return m_documentView; } void TikzKTextEditorView::setDocumentModified(KTextEditor::Document *doc) { - Q_EMIT modificationChanged(doc->isModified()); + Q_EMIT modificationChanged(doc->isModified()); } void TikzKTextEditorView::updateCompleter(bool useCompletion, const QStringList &words) { - m_completion->updateCompleter(useCompletion, words); + m_completion->updateCompleter(useCompletion, words); } void TikzKTextEditorView::clear() { - editor()->clear(); + editor()->clear(); } bool TikzKTextEditorView::isEmpty() { - return document()->isEmpty(); + return document()->isEmpty(); } bool TikzKTextEditorView::isModified() { - return document()->isModified(); + return document()->isModified(); } -void TikzKTextEditorView::setModified( bool value ) +void TikzKTextEditorView::setModified(bool value) { - return document()->setModified( value ); + return document()->setModified(value); } diff --git a/app/tikzktexteditorview.h b/app/tikzktexteditorview.h index 5a9f6ec..043b9da 100644 --- a/app/tikzktexteditorview.h +++ b/app/tikzktexteditorview.h @@ -29,43 +29,42 @@ class TikzKTextEditorCompletion; #include "tikzeditorviewabstract.h" -class TikzKTextEditorView: public TikzEditorViewAbstract +class TikzKTextEditorView : public TikzEditorViewAbstract { - Q_OBJECT + Q_OBJECT public: - explicit TikzKTextEditorView(QWidget *parent = 0); - virtual ~TikzKTextEditorView(); + explicit TikzKTextEditorView(QWidget *parent = 0); + virtual ~TikzKTextEditorView(); - KTextEditor::Document *editor(); - KTextEditor::Document *document(); - QString text(); - KTextEditor::View *view(); + KTextEditor::Document *editor(); + KTextEditor::Document *document(); + QString text(); + KTextEditor::View *view(); - void updateCompleter(bool useCompletion, const QStringList &words); - void clear(); - bool isEmpty(); - bool isModified(); - void setModified(bool value); + void updateCompleter(bool useCompletion, const QStringList &words); + void clear(); + bool isEmpty(); + bool isModified(); + void setModified(bool value); Q_SIGNALS: - void documentUrlChanged(const QUrl& url); - void modificationChanged(bool changed); - void contentsChanged(); - void cursorPositionChanged(int row, int col); - void showStatusMessage(const QString &message, int timeout = 3000); - void setSearchFromBegin(bool searchFromBegin); - void focusIn(); - void focusOut(); + void documentUrlChanged(const QUrl &url); + void modificationChanged(bool changed); + void contentsChanged(); + void cursorPositionChanged(int row, int col); + void showStatusMessage(const QString &message, int timeout = 3000); + void setSearchFromBegin(bool searchFromBegin); + void focusIn(); + void focusOut(); private Q_SLOTS: - void setDocumentModified(KTextEditor::Document *); + void setDocumentModified(KTextEditor::Document *); private: - KTextEditor::Document *m_currentDoc; - KTextEditor::View *m_documentView; - TikzKTextEditorCompletion *m_completion; - + KTextEditor::Document *m_currentDoc; + KTextEditor::View *m_documentView; + TikzKTextEditorCompletion *m_completion; }; #endif diff --git a/app/usercommandeditdialog.cpp b/app/usercommandeditdialog.cpp index 4164ef3..25a1ecd 100644 --- a/app/usercommandeditdialog.cpp +++ b/app/usercommandeditdialog.cpp @@ -22,142 +22,133 @@ static const QString s_completionPlaceHolder(0x2022); -UserCommandEditDialog::UserCommandEditDialog(QWidget *parent) - : QDialog(parent), - m_oldIndex(-1) +UserCommandEditDialog::UserCommandEditDialog(QWidget *parent) : QDialog(parent), m_oldIndex(-1) { - setModal(true); - ui.setupUi(this); + setModal(true); + ui.setupUi(this); - ui.comboBoxItem->setMinimumContentsLength(QString(tr("Menu item 100")).length()); + ui.comboBoxItem->setMinimumContentsLength(QString(tr("Menu item 100")).length()); - connect(ui.pushButtonAdd, SIGNAL(clicked()), this, SLOT(addItem())); - connect(ui.pushButtonRemove, SIGNAL(clicked()), this, SLOT(removeItem())); - connect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); - connect(ui.pushButtonInsertPlaceHolder, SIGNAL(clicked()), this, SLOT(insertPlaceHolder())); - connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(ui.pushButtonAdd, SIGNAL(clicked()), this, SLOT(addItem())); + connect(ui.pushButtonRemove, SIGNAL(clicked()), this, SLOT(removeItem())); + connect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); + connect(ui.pushButtonInsertPlaceHolder, SIGNAL(clicked()), this, SLOT(insertPlaceHolder())); + connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - readSettings(); + readSettings(); } void UserCommandEditDialog::readSettings() { - disconnect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); - QSettings settings; - int size = settings.beginReadArray(QLatin1String("UserCommands")); - ui.comboBoxItem->clear(); - for (int i = 0; i < size; ++i) - { - settings.setArrayIndex(i); - m_names.append(settings.value(QLatin1String("Name")).toString()); - m_commands.append(settings.value(QLatin1String("Command")).toString()); - - ui.comboBoxItem->insertItem(i, QString(tr("Menu item %1").arg(QString::number(i+1)))); - } - settings.endArray(); - connect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); - - if (m_names.size() > 0) - { - setEditingEnabled(true); - ui.comboBoxItem->setCurrentIndex(0); - ui.lineEditName->setText(m_names.at(0)); - ui.textEditContent->setPlainText(m_commands.at(0)); - m_oldIndex = 0; - } - else - setEditingEnabled(false); + disconnect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); + QSettings settings; + int size = settings.beginReadArray(QLatin1String("UserCommands")); + ui.comboBoxItem->clear(); + for (int i = 0; i < size; ++i) { + settings.setArrayIndex(i); + m_names.append(settings.value(QLatin1String("Name")).toString()); + m_commands.append(settings.value(QLatin1String("Command")).toString()); + + ui.comboBoxItem->insertItem(i, QString(tr("Menu item %1").arg(QString::number(i + 1)))); + } + settings.endArray(); + connect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); + + if (m_names.size() > 0) { + setEditingEnabled(true); + ui.comboBoxItem->setCurrentIndex(0); + ui.lineEditName->setText(m_names.at(0)); + ui.textEditContent->setPlainText(m_commands.at(0)); + m_oldIndex = 0; + } else + setEditingEnabled(false); } void UserCommandEditDialog::writeSettings() { - if (m_oldIndex >= 0) - { - m_names[m_oldIndex] = ui.lineEditName->text(); - m_commands[m_oldIndex] = ui.textEditContent->toPlainText(); - } - - QSettings settings; - settings.beginWriteArray(QLatin1String("UserCommands")); - settings.remove(QString()); // remove old entries (especially useful when the number of entries decreases) - for (int i = 0; i < m_names.size(); ++i) - { - settings.setArrayIndex(i); - settings.setValue(QLatin1String("Name"), m_names.at(i)); - settings.setValue(QLatin1String("Command"), m_commands.at(i)); - } - settings.endArray(); + if (m_oldIndex >= 0) { + m_names[m_oldIndex] = ui.lineEditName->text(); + m_commands[m_oldIndex] = ui.textEditContent->toPlainText(); + } + + QSettings settings; + settings.beginWriteArray(QLatin1String("UserCommands")); + settings.remove(QString()); // remove old entries (especially useful when the number of entries + // decreases) + for (int i = 0; i < m_names.size(); ++i) { + settings.setArrayIndex(i); + settings.setValue(QLatin1String("Name"), m_names.at(i)); + settings.setValue(QLatin1String("Command"), m_commands.at(i)); + } + settings.endArray(); } void UserCommandEditDialog::accept() { - if (m_names.size() > 0 && m_oldIndex >= 0) - { - m_names[m_oldIndex] = ui.lineEditName->text(); - m_commands[m_oldIndex] = ui.textEditContent->toPlainText(); - } - writeSettings(); - QDialog::accept(); + if (m_names.size() > 0 && m_oldIndex >= 0) { + m_names[m_oldIndex] = ui.lineEditName->text(); + m_commands[m_oldIndex] = ui.textEditContent->toPlainText(); + } + writeSettings(); + QDialog::accept(); } void UserCommandEditDialog::setEditingEnabled(bool enabled) { - ui.labelItem->setEnabled(enabled); - ui.comboBoxItem->setEnabled(enabled); - ui.labelName->setEnabled(enabled); - ui.lineEditName->setEnabled(enabled); - ui.labelContent->setEnabled(enabled); - ui.pushButtonInsertPlaceHolder->setEnabled(enabled); - ui.textEditContent->setEnabled(enabled); + ui.labelItem->setEnabled(enabled); + ui.comboBoxItem->setEnabled(enabled); + ui.labelName->setEnabled(enabled); + ui.lineEditName->setEnabled(enabled); + ui.labelContent->setEnabled(enabled); + ui.pushButtonInsertPlaceHolder->setEnabled(enabled); + ui.textEditContent->setEnabled(enabled); } void UserCommandEditDialog::addItem() { - const int index = ui.comboBoxItem->count(); - m_names.append(QString()); - m_commands.append(QString()); - ui.comboBoxItem->addItem(QString(tr("Menu item %1").arg(QString::number(index+1)))); - ui.comboBoxItem->setCurrentIndex(index); - setEditingEnabled(true); + const int index = ui.comboBoxItem->count(); + m_names.append(QString()); + m_commands.append(QString()); + ui.comboBoxItem->addItem(QString(tr("Menu item %1").arg(QString::number(index + 1)))); + ui.comboBoxItem->setCurrentIndex(index); + setEditingEnabled(true); } void UserCommandEditDialog::removeItem() { - disconnect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); + disconnect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); - int index = ui.comboBoxItem->currentIndex(); - m_names.removeAt(index); - m_commands.removeAt(index); - ui.comboBoxItem->removeItem(index); + int index = ui.comboBoxItem->currentIndex(); + m_names.removeAt(index); + m_commands.removeAt(index); + ui.comboBoxItem->removeItem(index); - if (index >= m_names.size()) - { - --index; - --m_oldIndex; - } - ui.lineEditName->setText(index >= 0 ? m_names.at(index) : QString()); - ui.textEditContent->setPlainText(index >= 0 ? m_commands.at(index) : QString()); + if (index >= m_names.size()) { + --index; + --m_oldIndex; + } + ui.lineEditName->setText(index >= 0 ? m_names.at(index) : QString()); + ui.textEditContent->setPlainText(index >= 0 ? m_commands.at(index) : QString()); - if (index < 0) - setEditingEnabled(false); + if (index < 0) + setEditingEnabled(false); - connect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); + connect(ui.comboBoxItem, SIGNAL(currentIndexChanged(int)), this, SLOT(changeItem(int))); } void UserCommandEditDialog::changeItem(int index) { - if (m_oldIndex >= 0) - { - m_names[m_oldIndex] = ui.lineEditName->text(); - m_commands[m_oldIndex] = ui.textEditContent->toPlainText(); - } - ui.lineEditName->setText(m_names.at(index)); - ui.textEditContent->setPlainText(m_commands.at(index)); - m_oldIndex = index; + if (m_oldIndex >= 0) { + m_names[m_oldIndex] = ui.lineEditName->text(); + m_commands[m_oldIndex] = ui.textEditContent->toPlainText(); + } + ui.lineEditName->setText(m_names.at(index)); + ui.textEditContent->setPlainText(m_commands.at(index)); + m_oldIndex = index; } void UserCommandEditDialog::insertPlaceHolder() { - ui.textEditContent->insertPlainText(s_completionPlaceHolder); - ui.textEditContent->setFocus(); + ui.textEditContent->insertPlainText(s_completionPlaceHolder); + ui.textEditContent->setFocus(); } diff --git a/app/usercommandeditdialog.h b/app/usercommandeditdialog.h index e108527..0453444 100644 --- a/app/usercommandeditdialog.h +++ b/app/usercommandeditdialog.h @@ -25,29 +25,29 @@ class QMenu; class UserCommandEditDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit UserCommandEditDialog(QWidget *parent = 0); + explicit UserCommandEditDialog(QWidget *parent = 0); - Ui::UserCommandEditDialog ui; + Ui::UserCommandEditDialog ui; public Q_SLOTS: - void accept(); + void accept(); private Q_SLOTS: - void readSettings(); - void writeSettings(); - void setEditingEnabled(bool enabled); - void addItem(); - void removeItem(); - void changeItem(int index); - void insertPlaceHolder(); + void readSettings(); + void writeSettings(); + void setEditingEnabled(bool enabled); + void addItem(); + void removeItem(); + void changeItem(int index); + void insertPlaceHolder(); private: - QStringList m_names; - QStringList m_commands; - int m_oldIndex; + QStringList m_names; + QStringList m_commands; + int m_oldIndex; }; -#endif //USERCOMMANDEDITDIALOG_H +#endif // USERCOMMANDEDITDIALOG_H diff --git a/app/usercommandinserter.cpp b/app/usercommandinserter.cpp index bdc7398..9af0ef4 100644 --- a/app/usercommandinserter.cpp +++ b/app/usercommandinserter.cpp @@ -27,54 +27,50 @@ static const QString s_completionPlaceHolder(0x2022); -UserCommandInserter::UserCommandInserter(QWidget *parent) - : QObject(parent) - , m_userMenu(0) +UserCommandInserter::UserCommandInserter(QWidget *parent) : QObject(parent), m_userMenu(0) { - readSettings(); + readSettings(); } void UserCommandInserter::readSettings() { - m_names.clear(); - m_commands.clear(); - QSettings settings; - const int size = settings.beginReadArray(QLatin1String("UserCommands")); - for (int i = 0; i < size; ++i) - { - settings.setArrayIndex(i); - m_names.append(settings.value(QLatin1String("Name")).toString()); - m_commands.append(settings.value(QLatin1String("Command")).toString()); - } - settings.endArray(); - - if (m_userMenu) - updateMenu(); + m_names.clear(); + m_commands.clear(); + QSettings settings; + const int size = settings.beginReadArray(QLatin1String("UserCommands")); + for (int i = 0; i < size; ++i) { + settings.setArrayIndex(i); + m_names.append(settings.value(QLatin1String("Name")).toString()); + m_commands.append(settings.value(QLatin1String("Command")).toString()); + } + settings.endArray(); + + if (m_userMenu) + updateMenu(); } QMenu *UserCommandInserter::getMenu() { - if (!m_userMenu) - m_userMenu = new QMenu(tr("&User snippets"), qobject_cast(parent())); - updateMenu(); - return m_userMenu; + if (!m_userMenu) + m_userMenu = new QMenu(tr("&User snippets"), qobject_cast(parent())); + updateMenu(); + return m_userMenu; } void UserCommandInserter::updateMenu() { - m_userMenu->clear(); + m_userMenu->clear(); - for (int i = 0; i < m_names.size(); ++i) - { - QAction *action = m_userMenu->addAction(m_names.at(i)); - action->setData(i); - connect(action, SIGNAL(triggered()), this, SLOT(insertTag())); - } + for (int i = 0; i < m_names.size(); ++i) { + QAction *action = m_userMenu->addAction(m_names.at(i)); + action->setData(i); + connect(action, SIGNAL(triggered()), this, SLOT(insertTag())); + } - m_userMenu->addSeparator(); + m_userMenu->addSeparator(); - QAction *action = m_userMenu->addAction(tr("&Edit user commands")); - connect(action, SIGNAL(triggered()), this, SLOT(editCommands())); + QAction *action = m_userMenu->addAction(tr("&Edit user commands")); + connect(action, SIGNAL(triggered()), this, SLOT(editCommands())); } /* @@ -83,7 +79,7 @@ void UserCommandInserter::updateMenu() QStringList UserCommandInserter::getCommandWords() { - return m_commands; + return m_commands; } /* @@ -92,19 +88,19 @@ QStringList UserCommandInserter::getCommandWords() void UserCommandInserter::insertTag() { - QAction *action = qobject_cast(sender()); - if (!action) - return; - Q_EMIT insertTag(m_commands.at(action->data().toInt())); + QAction *action = qobject_cast(sender()); + if (!action) + return; + Q_EMIT insertTag(m_commands.at(action->data().toInt())); } void UserCommandInserter::editCommands() { - QPointer editDialog = new UserCommandEditDialog(qobject_cast(parent())); - if (editDialog->exec()) - { - readSettings(); - Q_EMIT updateCompleter(); - } - delete editDialog; + QPointer editDialog = + new UserCommandEditDialog(qobject_cast(parent())); + if (editDialog->exec()) { + readSettings(); + Q_EMIT updateCompleter(); + } + delete editDialog; } diff --git a/app/usercommandinserter.h b/app/usercommandinserter.h index 612ebac..859879d 100644 --- a/app/usercommandinserter.h +++ b/app/usercommandinserter.h @@ -26,29 +26,29 @@ class QMenu; class UserCommandInserter : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit UserCommandInserter(QWidget *parent = 0); + explicit UserCommandInserter(QWidget *parent = 0); - void readSettings(); - QMenu *getMenu(); - QStringList getCommandWords(); + void readSettings(); + QMenu *getMenu(); + QStringList getCommandWords(); Q_SIGNALS: - void updateCompleter(); - void insertTag(const QString &tag); + void updateCompleter(); + void insertTag(const QString &tag); private Q_SLOTS: - void insertTag(); - void editCommands(); + void insertTag(); + void editCommands(); private: - void updateMenu(); + void updateMenu(); - QMenu *m_userMenu; - QStringList m_names; - QStringList m_commands; + QMenu *m_userMenu; + QStringList m_names; + QStringList m_commands; }; -#endif //USERCOMMANDINSERTER_H +#endif // USERCOMMANDINSERTER_H diff --git a/common/mainwidget.h b/common/mainwidget.h index 665162d..b7d3e81 100644 --- a/common/mainwidget.h +++ b/common/mainwidget.h @@ -28,20 +28,11 @@ class MainWidget : TextCodecProfile { public: - virtual ~MainWidget() {} + virtual ~MainWidget() { } - virtual QWidget *widget() - { - return new QWidget(); - } - virtual QString tikzCode() const - { - return QString(); - } - virtual QUrl url() const - { - return QUrl(); - } + virtual QWidget *widget() { return new QWidget(); } + virtual QString tikzCode() const { return QString(); } + virtual QUrl url() const { return QUrl(); } }; #endif diff --git a/common/templatewidget.cpp b/common/templatewidget.cpp index 514ea07..8bbbd2e 100644 --- a/common/templatewidget.cpp +++ b/common/templatewidget.cpp @@ -19,8 +19,8 @@ #include "templatewidget.h" #ifdef KTIKZ_USE_KDE -#include -#include +# include +# include #endif #include @@ -39,160 +39,165 @@ TemplateWidget::TemplateWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); - ui.templateCombo->setEditable(true); - ui.templateCombo->lineEdit()->setClearButtonEnabled(true); - ui.templateCombo->setMinimumContentsLength(20); - ui.templateChooseButton->setIcon(Icon(QLatin1String("document-open"))); + ui.setupUi(this); + ui.templateCombo->setEditable(true); + ui.templateCombo->lineEdit()->setClearButtonEnabled(true); + ui.templateCombo->setMinimumContentsLength(20); + ui.templateChooseButton->setIcon(Icon(QLatin1String("document-open"))); #ifdef KTIKZ_KPART - ui.templateReloadButton->setVisible(false); + ui.templateReloadButton->setVisible(false); #else - ui.templateReloadButton->setIcon(Icon(QLatin1String("view-refresh"))); + ui.templateReloadButton->setIcon(Icon(QLatin1String("view-refresh"))); #endif - ui.templateEditButton->setIcon(Icon(QLatin1String("document-edit"))); + ui.templateEditButton->setIcon(Icon(QLatin1String("document-edit"))); - m_urlCompletion = new UrlCompletion(this); - ui.templateCombo->setCompletionObject(m_urlCompletion); + m_urlCompletion = new UrlCompletion(this); + ui.templateCombo->setCompletionObject(m_urlCompletion); - connect(ui.templateChooseButton, SIGNAL(clicked()), - this, SLOT(selectTemplateFile())); - connect(ui.templateEditButton, SIGNAL(clicked()), - this, SLOT(editTemplateFile())); - connect(ui.templateReloadButton, SIGNAL(clicked()), - this, SLOT(reloadTemplateFile())); - connect(ui.templateCombo->lineEdit(), SIGNAL(textChanged(QString)), - this, SIGNAL(fileNameChanged(QString))); + connect(ui.templateChooseButton, SIGNAL(clicked()), this, SLOT(selectTemplateFile())); + connect(ui.templateEditButton, SIGNAL(clicked()), this, SLOT(editTemplateFile())); + connect(ui.templateReloadButton, SIGNAL(clicked()), this, SLOT(reloadTemplateFile())); + connect(ui.templateCombo->lineEdit(), SIGNAL(textChanged(QString)), this, + SIGNAL(fileNameChanged(QString))); - readRecentTemplates(); + readRecentTemplates(); } TemplateWidget::~TemplateWidget() { - saveRecentTemplates(); - delete m_urlCompletion; + saveRecentTemplates(); + delete m_urlCompletion; } QWidget *TemplateWidget::lastTabOrderWidget() { - return ui.templateEditButton; + return ui.templateEditButton; } void TemplateWidget::readRecentTemplates() { - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - ui.templateCombo->setMaxCount(settings.value(QLatin1String("TemplateRecentNumber"), 10).toInt()); - const QStringList templateRecentList = settings.value(QLatin1String("TemplateRecent")).toStringList(); - ui.templateCombo->addItems(templateRecentList); - const int index = templateRecentList.indexOf(settings.value(QLatin1String("TemplateFile")).toString()); - ui.templateCombo->setCurrentIndex(index >= 0 ? index : 0); + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + ui.templateCombo->setMaxCount( + settings.value(QLatin1String("TemplateRecentNumber"), 10).toInt()); + const QStringList templateRecentList = + settings.value(QLatin1String("TemplateRecent")).toStringList(); + ui.templateCombo->addItems(templateRecentList); + const int index = + templateRecentList.indexOf(settings.value(QLatin1String("TemplateFile")).toString()); + ui.templateCombo->setCurrentIndex(index >= 0 ? index : 0); } void TemplateWidget::saveRecentTemplates() { - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - QStringList recentTemplates; - for (int i = 0; i < ui.templateCombo->count(); ++i) - recentTemplates << ui.templateCombo->itemText(i); - settings.setValue(QLatin1String("TemplateRecent"), recentTemplates); - settings.setValue(QLatin1String("TemplateFile"), ui.templateCombo->lineEdit()->text()); + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + QStringList recentTemplates; + for (int i = 0; i < ui.templateCombo->count(); ++i) + recentTemplates << ui.templateCombo->itemText(i); + settings.setValue(QLatin1String("TemplateRecent"), recentTemplates); + settings.setValue(QLatin1String("TemplateFile"), ui.templateCombo->lineEdit()->text()); } void TemplateWidget::setFileName(const QString &fileName) { - disconnect(ui.templateCombo->lineEdit(), SIGNAL(textChanged(QString)), - this, SIGNAL(fileNameChanged(QString))); - const int index = ui.templateCombo->findText(fileName); - if (index >= 0) // then remove item in order to re-add it at the top - ui.templateCombo->removeItem(index); - ui.templateCombo->insertItem(0, fileName); - ui.templateCombo->lineEdit()->setText(QString()); - connect(ui.templateCombo->lineEdit(), SIGNAL(textChanged(QString)), - this, SIGNAL(fileNameChanged(QString))); - ui.templateCombo->setCurrentIndex(0); + disconnect(ui.templateCombo->lineEdit(), SIGNAL(textChanged(QString)), this, + SIGNAL(fileNameChanged(QString))); + const int index = ui.templateCombo->findText(fileName); + if (index >= 0) // then remove item in order to re-add it at the top + ui.templateCombo->removeItem(index); + ui.templateCombo->insertItem(0, fileName); + ui.templateCombo->lineEdit()->setText(QString()); + connect(ui.templateCombo->lineEdit(), SIGNAL(textChanged(QString)), this, + SIGNAL(fileNameChanged(QString))); + ui.templateCombo->setCurrentIndex(0); } void TemplateWidget::setReplaceText(const QString &replace) { - const QString templateDescription(tr("

The template contains the code " - "of a complete LaTeX document in which the TikZ picture will be " - "included and which will be typesetted to produce the preview " - "image. The string %1 in the template will be replaced by the " - "TikZ code.

") - .arg(replace.toHtmlEscaped())); - ui.templateCombo->setWhatsThis(tr("

Give the file name of the LaTeX " - "template. If this input field is empty or contains an invalid " - "file name, an internal default template will be used.

") - + templateDescription); - ui.templateLabel->setWhatsThis(ui.templateCombo->whatsThis()); - ui.templateEditButton->setWhatsThis(tr("

Edit this template with " - "an external editor specified in the \"Configure\" dialog.

") - + templateDescription); + const QString templateDescription( + tr("

The template contains the code " + "of a complete LaTeX document in which the TikZ picture will be " + "included and which will be typesetted to produce the preview " + "image. The string %1 in the template will be replaced by the " + "TikZ code.

") + .arg(replace.toHtmlEscaped())); + ui.templateCombo->setWhatsThis( + tr("

Give the file name of the LaTeX " + "template. If this input field is empty or contains an invalid " + "file name, an internal default template will be used.

") + + templateDescription); + ui.templateLabel->setWhatsThis(ui.templateCombo->whatsThis()); + ui.templateEditButton->setWhatsThis( + tr("

Edit this template with " + "an external editor specified in the \"Configure\" dialog.

") + + templateDescription); #ifdef KTIKZ_KPART - // dirty hack: make the following strings translated in the kpart: - ui.templateLabel->setText(tr("&Template:")); - ui.templateChooseButton->setWhatsThis(tr("

Browse to an existing template file.

")); - ui.templateChooseButton->setToolTip(tr("Select template file")); - ui.templateEditButton->setToolTip(tr("Edit template file")); + // dirty hack: make the following strings translated in the kpart: + ui.templateLabel->setText(tr("&Template:")); + ui.templateChooseButton->setWhatsThis(tr("

Browse to an existing template file.

")); + ui.templateChooseButton->setToolTip(tr("Select template file")); + ui.templateEditButton->setToolTip(tr("Edit template file")); #endif } void TemplateWidget::setEditor(const QString &editor) { - m_editor = editor; + m_editor = editor; } QString TemplateWidget::fileName() const { - return ui.templateCombo->currentText(); + return ui.templateCombo->currentText(); } void TemplateWidget::selectTemplateFile() { - QString currentFileName = ui.templateCombo->currentText(); + QString currentFileName = ui.templateCombo->currentText(); #ifdef KTIKZ_TEMPLATES_INSTALL_DIR - if (currentFileName.isEmpty() && QFileInfo(QString::fromLocal8Bit(KTIKZ_TEMPLATES_INSTALL_DIR)).isDir()) - currentFileName = QString::fromLocal8Bit(KTIKZ_TEMPLATES_INSTALL_DIR); + if (currentFileName.isEmpty() + && QFileInfo(QString::fromLocal8Bit(KTIKZ_TEMPLATES_INSTALL_DIR)).isDir()) + currentFileName = QString::fromLocal8Bit(KTIKZ_TEMPLATES_INSTALL_DIR); #endif - const Url url = FileDialog::getOpenUrl(this, - tr("Select a template file"), Url(currentFileName), - QString(QLatin1String("*.pgs *.tex|%1\n*|%2")) - .arg(tr("%1 template files").arg(QCoreApplication::applicationName())) - .arg(tr("All files"))); - if (url.isValid()) - setFileName(url.pathOrUrl()); + const Url url = FileDialog::getOpenUrl( + this, tr("Select a template file"), Url(currentFileName), + QString(QLatin1String("*.pgs *.tex|%1\n*|%2")) + .arg(tr("%1 template files").arg(QCoreApplication::applicationName())) + .arg(tr("All files"))); + if (url.isValid()) + setFileName(url.pathOrUrl()); } void TemplateWidget::editTemplateFile() { - QApplication::setOverrideCursor(Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); - QStringList editorArguments; - editorArguments << ui.templateCombo->currentText(); + QStringList editorArguments; + editorArguments << ui.templateCombo->currentText(); #ifdef KTIKZ_USE_KDE - #if ( (KIO_VERSION_MAJOR >= 5) && ( KIO_VERSION_MINOR > 31 ) ) - KRun::runUrl( Url( fileName() ), QStringLiteral( "text/plain" ), NULL, KRun::RunExecutables, QString() ); +# if ((KIO_VERSION_MAJOR >= 5) && (KIO_VERSION_MINOR > 31)) + KRun::runUrl(Url(fileName()), QStringLiteral("text/plain"), NULL, KRun::RunExecutables, + QString()); +# else + KRun::runUrl(Url(fileName()), QStringLiteral("text/plain"), NULL, 0); +# endif #else - KRun::runUrl( Url( fileName() ), QStringLiteral( "text/plain" ), NULL, 0 ); -#endif -#else - QProcess process; - process.startDetached(m_editor, editorArguments); + QProcess process; + process.startDetached(m_editor, editorArguments); #endif - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void TemplateWidget::reloadTemplateFile() { - setFileName(fileName()); + setFileName(fileName()); } void TemplateWidget::keyPressEvent(QKeyEvent *event) { - if (event->key() == Qt::Key_Return) - setFileName(ui.templateCombo->currentText()); - if (event->key() == Qt::Key_Escape || event->key() == Qt::Key_Return) - Q_EMIT focusEditor(); - QWidget::keyPressEvent(event); + if (event->key() == Qt::Key_Return) + setFileName(ui.templateCombo->currentText()); + if (event->key() == Qt::Key_Escape || event->key() == Qt::Key_Return) + Q_EMIT focusEditor(); + QWidget::keyPressEvent(event); } diff --git a/common/templatewidget.h b/common/templatewidget.h index a739091..6371716 100644 --- a/common/templatewidget.h +++ b/common/templatewidget.h @@ -25,37 +25,37 @@ class UrlCompletion; class TemplateWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit TemplateWidget(QWidget *parent = 0); - ~TemplateWidget(); - QWidget *lastTabOrderWidget(); - void setFileName(const QString &fileName); - void setReplaceText(const QString &replace); - void setEditor(const QString &editor); - QString fileName() const; + explicit TemplateWidget(QWidget *parent = 0); + ~TemplateWidget(); + QWidget *lastTabOrderWidget(); + void setFileName(const QString &fileName); + void setReplaceText(const QString &replace); + void setEditor(const QString &editor); + QString fileName() const; Q_SIGNALS: - void fileNameChanged(const QString &fileName); - void focusEditor(); + void fileNameChanged(const QString &fileName); + void focusEditor(); protected: - void keyPressEvent(QKeyEvent *event); + void keyPressEvent(QKeyEvent *event); private Q_SLOTS: - void selectTemplateFile(); - void editTemplateFile(); - void reloadTemplateFile(); + void selectTemplateFile(); + void editTemplateFile(); + void reloadTemplateFile(); private: - void readRecentTemplates(); - void saveRecentTemplates(); + void readRecentTemplates(); + void saveRecentTemplates(); - Ui::TemplateWidget ui; - UrlCompletion *m_urlCompletion; + Ui::TemplateWidget ui; + UrlCompletion *m_urlCompletion; - QString m_editor; + QString m_editor; }; #endif diff --git a/common/textcodecprofile.h b/common/textcodecprofile.h index 991bbcb..278bfac 100644 --- a/common/textcodecprofile.h +++ b/common/textcodecprofile.h @@ -21,20 +21,15 @@ class QTextStream; -class TextCodecProfile{ +class TextCodecProfile +{ public: - /// Configure a QTextStream to encode a TeX file. - /// @arg textStream A non-null instance of QTextStream. - void configureStreamEncoding(QTextStream& textStream) const - { - Q_UNUSED(textStream); - } - /// Configure a QTextStream to decode a TeX file. - /// @arg textStream A non-null instance of QTextStream. - void configureStreamDecoding(QTextStream& textStream) const - { - Q_UNUSED(textStream); - } + /// Configure a QTextStream to encode a TeX file. + /// @arg textStream A non-null instance of QTextStream. + void configureStreamEncoding(QTextStream &textStream) const { Q_UNUSED(textStream); } + /// Configure a QTextStream to decode a TeX file. + /// @arg textStream A non-null instance of QTextStream. + void configureStreamDecoding(QTextStream &textStream) const { Q_UNUSED(textStream); } }; #endif // TEXTCODECPROFILE_H diff --git a/common/tikzpreview.cpp b/common/tikzpreview.cpp index 7145d10..7590e96 100644 --- a/common/tikzpreview.cpp +++ b/common/tikzpreview.cpp @@ -28,7 +28,7 @@ #include #include -//#include "app/configeditorwidget.h" +// #include "app/configeditorwidget.h" #include "tikzpreviewrenderer.h" #include "utils/action.h" #include "utils/icon.h" @@ -36,407 +36,431 @@ #include "utils/zoomaction.h" TikzPreview::TikzPreview(QWidget *parent) - : QGraphicsView(parent) - , m_processRunning(false) - , m_pageSeparator(0) - , m_infoWidget(0) - , m_tikzPdfDoc(0) - , m_currentPage(0) - , m_oldZoomFactor(-1) - , m_hasZoomed(false) -{ - m_tikzScene = new QGraphicsScene(this); - m_tikzPixmapItem = m_tikzScene->addPixmap(QPixmap()); - setScene(m_tikzScene); - setDragMode(QGraphicsView::ScrollHandDrag); - m_tikzPixmapItem->setCursor(Qt::CrossCursor); - setWhatsThis(tr("

Here the preview image of " - "your TikZ code is shown. You can zoom in and out, and you " - "can scroll the image by dragging it.

")); - - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - settings.beginGroup(QLatin1String("Preview")); - m_zoomFactor = settings.value(QLatin1String("ZoomFactor"), 1).toDouble(); - setBackgroundColor(settings.value(QLatin1String("PreviewBackgroundColor"), QColor(Qt::white)).value()); - settings.endGroup(); - - createActions(); - - m_tikzPreviewRenderer = new TikzPreviewRenderer(); - connect(this, SIGNAL(generatePreview(Poppler::Document*,qreal,int)), m_tikzPreviewRenderer, SLOT(generatePreview(Poppler::Document*,qreal,int))); - connect(m_tikzPreviewRenderer, SIGNAL(showPreview(QImage,qreal)), this, SLOT(showPreview(QImage,qreal))); + : QGraphicsView(parent), + m_processRunning(false), + m_pageSeparator(0), + m_infoWidget(0), + m_tikzPdfDoc(0), + m_currentPage(0), + m_oldZoomFactor(-1), + m_hasZoomed(false) +{ + m_tikzScene = new QGraphicsScene(this); + m_tikzPixmapItem = m_tikzScene->addPixmap(QPixmap()); + setScene(m_tikzScene); + setDragMode(QGraphicsView::ScrollHandDrag); + m_tikzPixmapItem->setCursor(Qt::CrossCursor); + setWhatsThis(tr("

Here the preview image of " + "your TikZ code is shown. You can zoom in and out, and you " + "can scroll the image by dragging it.

")); + + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + settings.beginGroup(QLatin1String("Preview")); + m_zoomFactor = settings.value(QLatin1String("ZoomFactor"), 1).toDouble(); + setBackgroundColor(settings.value(QLatin1String("PreviewBackgroundColor"), QColor(Qt::white)) + .value()); + settings.endGroup(); + + createActions(); + + m_tikzPreviewRenderer = new TikzPreviewRenderer(); + connect(this, SIGNAL(generatePreview(Poppler::Document *, qreal, int)), m_tikzPreviewRenderer, + SLOT(generatePreview(Poppler::Document *, qreal, int))); + connect(m_tikzPreviewRenderer, SIGNAL(showPreview(QImage, qreal)), this, + SLOT(showPreview(QImage, qreal))); } TikzPreview::~TikzPreview() { - delete m_tikzPixmapItem; - delete m_infoWidget; - delete m_tikzPreviewRenderer; + delete m_tikzPixmapItem; + delete m_infoWidget; + delete m_tikzPreviewRenderer; - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - settings.beginGroup(QLatin1String("Preview")); - settings.setValue(QLatin1String("ZoomFactor"), m_zoomFactor); - settings.endGroup(); + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + settings.beginGroup(QLatin1String("Preview")); + settings.setValue(QLatin1String("ZoomFactor"), m_zoomFactor); + settings.endGroup(); } void TikzPreview::contextMenuEvent(QContextMenuEvent *event) { - QMenu *menu = new QMenu(this); - menu->addActions(actions()); - menu->exec(event->globalPos()); - menu->deleteLater(); + QMenu *menu = new QMenu(this); + menu->addActions(actions()); + menu->exec(event->globalPos()); + menu->deleteLater(); } QSize TikzPreview::sizeHint() const { - const int screenWidth = QApplication::desktop()->availableGeometry().width(); - if (screenWidth > 1200) - return QSize(500, 400); - else if (screenWidth > 1024) - return QSize(400, 400); - else - return QSize(250, 200); + const int screenWidth = QApplication::desktop()->availableGeometry().width(); + if (screenWidth > 1200) + return QSize(500, 400); + else if (screenWidth > 1024) + return QSize(400, 400); + else + return QSize(250, 200); } /***************************************************************************/ void TikzPreview::createActions() { - m_zoomInAction = StandardAction::zoomIn(this, SLOT(zoomIn()), this); - m_zoomOutAction = StandardAction::zoomOut(this, SLOT(zoomOut()), this); - m_zoomInAction->setStatusTip(tr("Zoom preview in")); - m_zoomOutAction->setStatusTip(tr("Zoom preview out")); - m_zoomInAction->setWhatsThis(tr("

Zoom preview in by a predetermined factor.

")); - m_zoomOutAction->setWhatsThis(tr("

Zoom preview out by a predetermined factor.

")); - - m_zoomToAction = new ZoomAction(Icon(QLatin1String("zoom-original")), tr("&Zoom"), this, QLatin1String("zoom_to")); - m_zoomToAction->setZoomFactor(m_zoomFactor); - connect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); - - m_previousPageAction = new Action(Icon(QLatin1String("go-previous")), tr("&Previous image"), this, QLatin1String("view_previous_image")); - m_previousPageAction->setShortcut(tr("Alt+Left", "View|Go to previous page")); - m_previousPageAction->setStatusTip(tr("Show previous image in preview")); - m_previousPageAction->setWhatsThis(tr("

Show the preview of the previous tikzpicture in the TikZ code.

")); - connect(m_previousPageAction, SIGNAL(triggered()), this, SLOT(showPreviousPage())); - - m_nextPageAction = new Action(Icon(QLatin1String("go-next")), tr("&Next image"), this, QLatin1String("view_next_image")); - m_nextPageAction->setShortcut(tr("Alt+Right", "View|Go to next page")); - m_nextPageAction->setStatusTip(tr("Show next image in preview")); - m_nextPageAction->setWhatsThis(tr("

Show the preview of the next tikzpicture in the TikZ code.

")); - connect(m_nextPageAction, SIGNAL(triggered()), this, SLOT(showNextPage())); - - m_previousPageAction->setVisible(false); - m_previousPageAction->setEnabled(false); - m_nextPageAction->setVisible(false); - m_nextPageAction->setEnabled(true); -} - -QList TikzPreview::actions() -{ - QList actions; - actions << m_zoomInAction << m_zoomOutAction; - QAction *action = new QAction(this); - action->setSeparator(true); - actions << action; - actions << m_previousPageAction << m_nextPageAction; - return actions; + m_zoomInAction = StandardAction::zoomIn(this, SLOT(zoomIn()), this); + m_zoomOutAction = StandardAction::zoomOut(this, SLOT(zoomOut()), this); + m_zoomInAction->setStatusTip(tr("Zoom preview in")); + m_zoomOutAction->setStatusTip(tr("Zoom preview out")); + m_zoomInAction->setWhatsThis(tr("

Zoom preview in by a predetermined factor.

")); + m_zoomOutAction->setWhatsThis(tr("

Zoom preview out by a predetermined factor.

")); + + m_zoomToAction = new ZoomAction(Icon(QLatin1String("zoom-original")), tr("&Zoom"), this, + QLatin1String("zoom_to")); + m_zoomToAction->setZoomFactor(m_zoomFactor); + connect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); + + m_previousPageAction = new Action(Icon(QLatin1String("go-previous")), tr("&Previous image"), + this, QLatin1String("view_previous_image")); + m_previousPageAction->setShortcut(tr("Alt+Left", "View|Go to previous page")); + m_previousPageAction->setStatusTip(tr("Show previous image in preview")); + m_previousPageAction->setWhatsThis( + tr("

Show the preview of the previous tikzpicture in the TikZ code.

")); + connect(m_previousPageAction, SIGNAL(triggered()), this, SLOT(showPreviousPage())); + + m_nextPageAction = new Action(Icon(QLatin1String("go-next")), tr("&Next image"), this, + QLatin1String("view_next_image")); + m_nextPageAction->setShortcut(tr("Alt+Right", "View|Go to next page")); + m_nextPageAction->setStatusTip(tr("Show next image in preview")); + m_nextPageAction->setWhatsThis( + tr("

Show the preview of the next tikzpicture in the TikZ code.

")); + connect(m_nextPageAction, SIGNAL(triggered()), this, SLOT(showNextPage())); + + m_previousPageAction->setVisible(false); + m_previousPageAction->setEnabled(false); + m_nextPageAction->setVisible(false); + m_nextPageAction->setEnabled(true); +} + +QList TikzPreview::actions() +{ + QList actions; + actions << m_zoomInAction << m_zoomOutAction; + QAction *action = new QAction(this); + action->setSeparator(true); + actions << action; + actions << m_previousPageAction << m_nextPageAction; + return actions; } QToolBar *TikzPreview::toolBar() { - QToolBar *viewToolBar = new QToolBar(tr("View"), this); - viewToolBar->setObjectName(QLatin1String("ViewToolBar")); - viewToolBar->addAction(m_zoomInAction); - viewToolBar->addAction(m_zoomToAction); - viewToolBar->addAction(m_zoomOutAction); - m_pageSeparator = viewToolBar->addSeparator(); - m_pageSeparator->setVisible(false); - viewToolBar->addAction(m_previousPageAction); - viewToolBar->addAction(m_nextPageAction); - return viewToolBar; + QToolBar *viewToolBar = new QToolBar(tr("View"), this); + viewToolBar->setObjectName(QLatin1String("ViewToolBar")); + viewToolBar->addAction(m_zoomInAction); + viewToolBar->addAction(m_zoomToAction); + viewToolBar->addAction(m_zoomOutAction); + m_pageSeparator = viewToolBar->addSeparator(); + m_pageSeparator->setVisible(false); + viewToolBar->addAction(m_previousPageAction); + viewToolBar->addAction(m_nextPageAction); + return viewToolBar; } /***************************************************************************/ void TikzPreview::paintEvent(QPaintEvent *event) { - if (m_hasZoomed) - { - setSceneRect(m_tikzScene->itemsBoundingRect()); // make sure that the scroll area is not bigger than the actual image - m_hasZoomed = false; - } - if (m_infoWidget && m_infoWidget->isVisible()) // make sure that if the error that Gnuplot is not found is shown at startup, then it is shown in the center of the view; this does not happen automatically because the error is generated before the main window becomes visible - centerInfoLabel(); + if (m_hasZoomed) { + setSceneRect(m_tikzScene->itemsBoundingRect()); // make sure that the scroll area is not + // bigger than the actual image + m_hasZoomed = false; + } + if (m_infoWidget + && m_infoWidget->isVisible()) // make sure that if the error that Gnuplot is not found is + // shown at startup, then it is shown in the center of the + // view; this does not happen automatically because the error + // is generated before the main window becomes visible + centerInfoLabel(); - QGraphicsView::paintEvent(event); + QGraphicsView::paintEvent(event); } /***************************************************************************/ void TikzPreview::setZoomFactor(qreal zoomFactor) { - m_zoomFactor = zoomFactor; - if (m_zoomFactor == m_oldZoomFactor) - return; + m_zoomFactor = zoomFactor; + if (m_zoomFactor == m_oldZoomFactor) + return; - m_zoomInAction->setEnabled(m_zoomFactor < m_zoomToAction->maxZoomFactor()); - m_zoomOutAction->setEnabled(m_zoomFactor > m_zoomToAction->minZoomFactor()); + m_zoomInAction->setEnabled(m_zoomFactor < m_zoomToAction->maxZoomFactor()); + m_zoomOutAction->setEnabled(m_zoomFactor > m_zoomToAction->minZoomFactor()); - showPdfPage(); + showPdfPage(); } void TikzPreview::zoomIn() { - m_zoomToAction->setZoomFactor(m_zoomFactor + (m_zoomFactor > 0.99 ? - (m_zoomFactor > 1.99 ? 0.5 : 0.2) : 0.1)); + m_zoomToAction->setZoomFactor( + m_zoomFactor + (m_zoomFactor > 0.99 ? (m_zoomFactor > 1.99 ? 0.5 : 0.2) : 0.1)); } void TikzPreview::zoomOut() { - m_zoomToAction->setZoomFactor(m_zoomFactor - (m_zoomFactor > 1.01 ? - (m_zoomFactor > 2.01 ? 0.5 : 0.2) : 0.1)); + m_zoomToAction->setZoomFactor( + m_zoomFactor - (m_zoomFactor > 1.01 ? (m_zoomFactor > 2.01 ? 0.5 : 0.2) : 0.1)); } /***************************************************************************/ void TikzPreview::showPreviousPage() { - if (m_currentPage > 0) - --m_currentPage; - m_previousPageAction->setEnabled(m_currentPage > 0); - m_nextPageAction->setEnabled(m_currentPage < m_tikzPdfDoc->numPages() - 1); - showPdfPage(); + if (m_currentPage > 0) + --m_currentPage; + m_previousPageAction->setEnabled(m_currentPage > 0); + m_nextPageAction->setEnabled(m_currentPage < m_tikzPdfDoc->numPages() - 1); + showPdfPage(); } void TikzPreview::showNextPage() { - if (m_currentPage < m_tikzPdfDoc->numPages() - 1) - ++m_currentPage; - m_previousPageAction->setEnabled(m_currentPage > 0); - m_nextPageAction->setEnabled(m_currentPage < m_tikzPdfDoc->numPages() - 1); - showPdfPage(); + if (m_currentPage < m_tikzPdfDoc->numPages() - 1) + ++m_currentPage; + m_previousPageAction->setEnabled(m_currentPage > 0); + m_nextPageAction->setEnabled(m_currentPage < m_tikzPdfDoc->numPages() - 1); + showPdfPage(); } void TikzPreview::showPreview(const QImage &tikzImage, qreal zoomFactor) { - // this slot is called when TikzPreviewRenderer has finished rendering - // the current pdf page to tikzImage, so before we actually display - // the image the old center point must be calculated and multiplied - // by the quotient of the new and old zoom factor in order to obtain - // the new center point of the image; the recentering itself is done - // at the end of this function - QPointF centerPoint(horizontalScrollBar()->value() + viewport()->width() * 0.5, - verticalScrollBar()->value() + viewport()->height() * 0.5); - const qreal zoomFraction = (m_oldZoomFactor > 0) ? zoomFactor / m_oldZoomFactor : 1; - if (!centerPoint.isNull()) - centerPoint *= zoomFraction; - m_oldZoomFactor = zoomFactor; // m_oldZoomFactor must be set here and not in the zoom functions in order to avoid skipping some steps when the user zooms fast - m_hasZoomed = true; - - // display and center the preview image - m_tikzPixmapItem->setPixmap(QPixmap::fromImage(tikzImage)); - centerOn(centerPoint); + // this slot is called when TikzPreviewRenderer has finished rendering + // the current pdf page to tikzImage, so before we actually display + // the image the old center point must be calculated and multiplied + // by the quotient of the new and old zoom factor in order to obtain + // the new center point of the image; the recentering itself is done + // at the end of this function + QPointF centerPoint(horizontalScrollBar()->value() + viewport()->width() * 0.5, + verticalScrollBar()->value() + viewport()->height() * 0.5); + const qreal zoomFraction = (m_oldZoomFactor > 0) ? zoomFactor / m_oldZoomFactor : 1; + if (!centerPoint.isNull()) + centerPoint *= zoomFraction; + m_oldZoomFactor = zoomFactor; // m_oldZoomFactor must be set here and not in the zoom functions + // in order to avoid skipping some steps when the user zooms fast + m_hasZoomed = true; + + // display and center the preview image + m_tikzPixmapItem->setPixmap(QPixmap::fromImage(tikzImage)); + centerOn(centerPoint); } void TikzPreview::showPdfPage() { - if (!m_tikzPdfDoc || m_tikzPdfDoc->numPages() < 1) - return; + if (!m_tikzPdfDoc || m_tikzPdfDoc->numPages() < 1) + return; - if (!m_processRunning) - Q_EMIT generatePreview(m_tikzPdfDoc, m_zoomFactor, m_currentPage); // render the current pdf page to a QImage in TikzPreviewRenderer (in a different thread) + if (!m_processRunning) + Q_EMIT generatePreview(m_tikzPdfDoc, m_zoomFactor, + m_currentPage); // render the current pdf page to a QImage in + // TikzPreviewRenderer (in a different thread) } void TikzPreview::emptyPreview() { - m_tikzPdfDoc = 0; - m_tikzCoordinates.clear(); - m_tikzPixmapItem->setPixmap(QPixmap()); - m_tikzPixmapItem->update(); - if (m_infoWidget) - m_infoWidget->setVisible(false); // remove error messages from view - setSceneRect(m_tikzScene->itemsBoundingRect()); // remove scrollbars from view - if (m_pageSeparator) - m_pageSeparator->setVisible(false); - m_previousPageAction->setVisible(false); - m_nextPageAction->setVisible(false); + m_tikzPdfDoc = 0; + m_tikzCoordinates.clear(); + m_tikzPixmapItem->setPixmap(QPixmap()); + m_tikzPixmapItem->update(); + if (m_infoWidget) + m_infoWidget->setVisible(false); // remove error messages from view + setSceneRect(m_tikzScene->itemsBoundingRect()); // remove scrollbars from view + if (m_pageSeparator) + m_pageSeparator->setVisible(false); + m_previousPageAction->setVisible(false); + m_nextPageAction->setVisible(false); } void TikzPreview::pixmapUpdated(Poppler::Document *tikzPdfDoc, const QList &tikzCoordinates) { - m_tikzPdfDoc = tikzPdfDoc; - m_tikzCoordinates = tikzCoordinates; + m_tikzPdfDoc = tikzPdfDoc; + m_tikzCoordinates = tikzCoordinates; - if (!m_tikzPdfDoc) - { - emptyPreview(); - return; - } + if (!m_tikzPdfDoc) { + emptyPreview(); + return; + } - m_tikzPdfDoc->setRenderBackend(Poppler::Document::SplashBackend); -// m_tikzPdfDoc->setRenderBackend(Poppler::Document::ArthurBackend); - m_tikzPdfDoc->setRenderHint(Poppler::Document::Antialiasing, true); - m_tikzPdfDoc->setRenderHint(Poppler::Document::TextAntialiasing, true); - const int numOfPages = m_tikzPdfDoc->numPages(); + m_tikzPdfDoc->setRenderBackend(Poppler::Document::SplashBackend); + // m_tikzPdfDoc->setRenderBackend(Poppler::Document::ArthurBackend); + m_tikzPdfDoc->setRenderHint(Poppler::Document::Antialiasing, true); + m_tikzPdfDoc->setRenderHint(Poppler::Document::TextAntialiasing, true); + const int numOfPages = m_tikzPdfDoc->numPages(); - const bool visible = (numOfPages > 1); - if (m_pageSeparator) - m_pageSeparator->setVisible(visible); - m_previousPageAction->setVisible(visible); - m_nextPageAction->setVisible(visible); + const bool visible = (numOfPages > 1); + if (m_pageSeparator) + m_pageSeparator->setVisible(visible); + m_previousPageAction->setVisible(visible); + m_nextPageAction->setVisible(visible); - if (m_currentPage >= numOfPages) // if the new tikz code has fewer tikzpictures than the previous one (this may happen if a new PGF file is opened in the same window), then we must reset m_currentPage - { - m_currentPage = 0; - m_previousPageAction->setEnabled(false); - m_nextPageAction->setEnabled(true); - } + if (m_currentPage >= numOfPages) // if the new tikz code has fewer tikzpictures than the + // previous one (this may happen if a new PGF file is opened in + // the same window), then we must reset m_currentPage + { + m_currentPage = 0; + m_previousPageAction->setEnabled(false); + m_nextPageAction->setEnabled(true); + } - showPdfPage(); + showPdfPage(); } /***************************************************************************/ QImage TikzPreview::renderToImage(double xres, double yres, int pageNumber) { - Poppler::Page *page = m_tikzPdfDoc->page(pageNumber); -// const QSizeF pageSize = page->pageSizeF(); -// const QImage image = pageSize.height() >= pageSize.width() -// ? page->renderToImage(xres, yres) -// : page->renderToImage(xres, yres, -1, -1, -1, -1, Poppler::Page::Rotate270); // slow - const QImage image = page->renderToImage(xres, yres); // slow - delete page; - return image; + Poppler::Page *page = m_tikzPdfDoc->page(pageNumber); + // const QSizeF pageSize = page->pageSizeF(); + // const QImage image = pageSize.height() >= pageSize.width() + // ? page->renderToImage(xres, yres) + // : page->renderToImage(xres, yres, -1, -1, -1, -1, Poppler::Page::Rotate270); // slow + const QImage image = page->renderToImage(xres, yres); // slow + delete page; + return image; } QPixmap TikzPreview::pixmap() const { - return m_tikzPixmapItem->pixmap(); + return m_tikzPixmapItem->pixmap(); } int TikzPreview::currentPage() const { - return m_currentPage; + return m_currentPage; } int TikzPreview::numberOfPages() const { - return m_tikzPdfDoc->numPages(); + return m_tikzPdfDoc->numPages(); } /***************************************************************************/ void TikzPreview::createInformationLabel() { - m_infoWidget = new TikzPreviewMessageWidget(this); - QGraphicsItem *infoProxyWidget = m_tikzScene->addWidget(m_infoWidget); - infoProxyWidget->setZValue(1); - m_infoWidget->setVisible(false); + m_infoWidget = new TikzPreviewMessageWidget(this); + QGraphicsItem *infoProxyWidget = m_tikzScene->addWidget(m_infoWidget); + infoProxyWidget->setZValue(1); + m_infoWidget->setVisible(false); } void TikzPreview::centerInfoLabel() { - const qreal posX = (viewport()->width() - m_infoWidget->width()) * 0.5; - const qreal posY = (viewport()->height() - m_infoWidget->height()) * 0.5; - m_infoWidget->move(posX, posY); + const qreal posX = (viewport()->width() - m_infoWidget->width()) * 0.5; + const qreal posY = (viewport()->height() - m_infoWidget->height()) * 0.5; + m_infoWidget->move(posX, posY); } -void TikzPreview::setInfoLabelText(const QString &message, TikzPreviewMessageWidget::PixmapVisibility pixmapVisibility) +void TikzPreview::setInfoLabelText(const QString &message, + TikzPreviewMessageWidget::PixmapVisibility pixmapVisibility) { - if (!m_infoWidget) - createInformationLabel(); - m_infoWidget->setText(message, pixmapVisibility); - m_infoWidget->setVisible(true); - centerInfoLabel(); // must be run here so that the label is always centered + if (!m_infoWidget) + createInformationLabel(); + m_infoWidget->setText(message, pixmapVisibility); + m_infoWidget->setVisible(true); + centerInfoLabel(); // must be run here so that the label is always centered } void TikzPreview::showErrorMessage(const QString &message) { - setInfoLabelText(message, TikzPreviewMessageWidget::PixmapVisible); + setInfoLabelText(message, TikzPreviewMessageWidget::PixmapVisible); } void TikzPreview::setProcessRunning(bool isRunning) { - m_processRunning = isRunning; - if (isRunning) - setInfoLabelText(tr("Generating image", "tikz preview status"), TikzPreviewMessageWidget::PixmapNotVisible); - else - m_infoWidget->setVisible(false); + m_processRunning = isRunning; + if (isRunning) + setInfoLabelText(tr("Generating image", "tikz preview status"), + TikzPreviewMessageWidget::PixmapNotVisible); + else + m_infoWidget->setVisible(false); } /***************************************************************************/ void TikzPreview::setShowCoordinates(bool show) { - m_showCoordinates = show; + m_showCoordinates = show; } void TikzPreview::setCoordinatePrecision(int precision) { - m_precision = precision; + m_precision = precision; } void TikzPreview::setBackgroundColor(QColor color) { - m_tikzScene->setBackgroundBrush(color); + m_tikzScene->setBackgroundBrush(color); } /***************************************************************************/ void TikzPreview::wheelEvent(QWheelEvent *event) { - if (event->modifiers() == Qt::ControlModifier) - { - if (event->delta() > 0) - zoomIn(); - else - zoomOut(); - } - else - QGraphicsView::wheelEvent(event); + if (event->modifiers() == Qt::ControlModifier) { + if (event->delta() > 0) + zoomIn(); + else + zoomOut(); + } else + QGraphicsView::wheelEvent(event); } void TikzPreview::mouseMoveEvent(QMouseEvent *event) { - const int offset = 6 * m_currentPage; - if (m_showCoordinates && m_tikzCoordinates.length() >= offset + 6) - { - const qreal unitX = m_tikzCoordinates.at(offset); // unit length in x-direction in points - const qreal unitY = m_tikzCoordinates.at(1 + offset); // unit length in y-direction in points - const qreal minX = m_tikzCoordinates.at(2 + offset); // minimum x-coordinate on the figure in points - const qreal maxX = m_tikzCoordinates.at(3 + offset); // maximum x-coordinate on the figure in points - const qreal minY = m_tikzCoordinates.at(4 + offset); // minimum y-coordinate on the figure in points - const qreal maxY = m_tikzCoordinates.at(5 + offset); // maximum y-coordinate on the figure in points - - if (unitX > 0 && unitY > 0) // this is not the case for 3D plots - { - int precisionX = m_precision; // the number of decimals used to display the x-coordinate of the mouse pointer - int precisionY = m_precision; // idem for the y-coordinate - if (m_precision < 0) // in app/configgeneralwidget.cpp the precision is set to -1 if the user chooses "Best precision", which we calculate now - { - qreal invUnitX = 1 / unitX; - qreal invUnitY = 1 / unitY; - for (precisionX = 0; invUnitX < 1; ++precisionX) // make sure that some significant decimals are displayed (and not numbers like 0.00) - invUnitX *= 10; - for (precisionY = 0; invUnitY < 1; ++precisionY) // idem - invUnitY *= 10; - } - - const QPointF mouseSceneCoords = mapToScene(event->pos()) / m_zoomFactor; - const qreal coordX = mouseSceneCoords.x() + minX; - const qreal coordY = maxY - mouseSceneCoords.y(); - if (coordX >= minX && coordX <= maxX && coordY >= minY && coordY <= maxY) - Q_EMIT showMouseCoordinates(coordX / unitX, coordY / unitY, precisionX, precisionY); - } - } - QGraphicsView::mouseMoveEvent(event); + const int offset = 6 * m_currentPage; + if (m_showCoordinates && m_tikzCoordinates.length() >= offset + 6) { + const qreal unitX = m_tikzCoordinates.at(offset); // unit length in x-direction in points + const qreal unitY = + m_tikzCoordinates.at(1 + offset); // unit length in y-direction in points + const qreal minX = + m_tikzCoordinates.at(2 + offset); // minimum x-coordinate on the figure in points + const qreal maxX = + m_tikzCoordinates.at(3 + offset); // maximum x-coordinate on the figure in points + const qreal minY = + m_tikzCoordinates.at(4 + offset); // minimum y-coordinate on the figure in points + const qreal maxY = + m_tikzCoordinates.at(5 + offset); // maximum y-coordinate on the figure in points + + if (unitX > 0 && unitY > 0) // this is not the case for 3D plots + { + int precisionX = m_precision; // the number of decimals used to display the x-coordinate + // of the mouse pointer + int precisionY = m_precision; // idem for the y-coordinate + if (m_precision < 0) // in app/configgeneralwidget.cpp the precision is set to -1 if the + // user chooses "Best precision", which we calculate now + { + qreal invUnitX = 1 / unitX; + qreal invUnitY = 1 / unitY; + for (precisionX = 0; invUnitX < 1; + ++precisionX) // make sure that some significant decimals are displayed (and + // not numbers like 0.00) + invUnitX *= 10; + for (precisionY = 0; invUnitY < 1; ++precisionY) // idem + invUnitY *= 10; + } + + const QPointF mouseSceneCoords = mapToScene(event->pos()) / m_zoomFactor; + const qreal coordX = mouseSceneCoords.x() + minX; + const qreal coordY = maxY - mouseSceneCoords.y(); + if (coordX >= minX && coordX <= maxX && coordY >= minY && coordY <= maxY) + Q_EMIT showMouseCoordinates(coordX / unitX, coordY / unitY, precisionX, precisionY); + } + } + QGraphicsView::mouseMoveEvent(event); } void TikzPreview::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::XButton1) - showPreviousPage(); - else if (event->button() == Qt::XButton2) - showNextPage(); - QGraphicsView::mousePressEvent(event); + if (event->button() == Qt::XButton1) + showPreviousPage(); + else if (event->button() == Qt::XButton2) + showNextPage(); + QGraphicsView::mousePressEvent(event); } diff --git a/common/tikzpreview.h b/common/tikzpreview.h index 71a7553..5a2d005 100644 --- a/common/tikzpreview.h +++ b/common/tikzpreview.h @@ -26,8 +26,7 @@ class QToolBar; -namespace Poppler -{ +namespace Poppler { class Document; } @@ -38,78 +37,81 @@ class TikzPreviewRenderer; class TikzPreview : public QGraphicsView { - Q_OBJECT + Q_OBJECT public: - explicit TikzPreview(QWidget *parent = 0); - ~TikzPreview(); - - virtual QSize sizeHint() const; - QList actions(); - QToolBar *toolBar(); - QImage renderToImage(double xres, double yres, int pageNumber); - QPixmap pixmap() const; - int currentPage() const; - int numberOfPages() const; - void emptyPreview(); - void setProcessRunning(bool isRunning); - void setShowCoordinates(bool show); - void setCoordinatePrecision(int precision); - void setBackgroundColor(QColor color); + explicit TikzPreview(QWidget *parent = 0); + ~TikzPreview(); + + virtual QSize sizeHint() const; + QList actions(); + QToolBar *toolBar(); + QImage renderToImage(double xres, double yres, int pageNumber); + QPixmap pixmap() const; + int currentPage() const; + int numberOfPages() const; + void emptyPreview(); + void setProcessRunning(bool isRunning); + void setShowCoordinates(bool show); + void setCoordinatePrecision(int precision); + void setBackgroundColor(QColor color); public Q_SLOTS: - void showPreview(const QImage &tikzImage, qreal zoomFactor = 1.0); - void pixmapUpdated(Poppler::Document *tikzPdfDoc, const QList &tikzCoordinates = QList()); - void showErrorMessage(const QString &message); + void showPreview(const QImage &tikzImage, qreal zoomFactor = 1.0); + void pixmapUpdated(Poppler::Document *tikzPdfDoc, + const QList &tikzCoordinates = QList()); + void showErrorMessage(const QString &message); Q_SIGNALS: - void showMouseCoordinates(qreal x, qreal y, int precisionX = 5, int precisionY = 5); - void generatePreview(Poppler::Document *tikzPdfDoc, qreal zoomFactor, int currentPage); + void showMouseCoordinates(qreal x, qreal y, int precisionX = 5, int precisionY = 5); + void generatePreview(Poppler::Document *tikzPdfDoc, qreal zoomFactor, int currentPage); protected: - void contextMenuEvent(QContextMenuEvent *event); - void paintEvent(QPaintEvent *event); - void wheelEvent(QWheelEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void mousePressEvent(QMouseEvent *event); + void contextMenuEvent(QContextMenuEvent *event); + void paintEvent(QPaintEvent *event); + void wheelEvent(QWheelEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void mousePressEvent(QMouseEvent *event); private Q_SLOTS: - void setZoomFactor(qreal zoomFactor); - void zoomIn(); - void zoomOut(); - void showPreviousPage(); - void showNextPage(); + void setZoomFactor(qreal zoomFactor); + void zoomIn(); + void zoomOut(); + void showPreviousPage(); + void showNextPage(); private: - void createInformationLabel(); - void createActions(); - void showPdfPage(); - void centerInfoLabel(); - void setInfoLabelText(const QString &message, TikzPreviewMessageWidget::PixmapVisibility pixmapVisibility = TikzPreviewMessageWidget::PixmapNotVisible); - - QGraphicsScene *m_tikzScene; - QGraphicsPixmapItem *m_tikzPixmapItem; - TikzPreviewRenderer *m_tikzPreviewRenderer; - bool m_processRunning; - - QAction *m_zoomInAction; - QAction *m_zoomOutAction; - ZoomAction *m_zoomToAction; - QAction *m_pageSeparator; - Action *m_previousPageAction; - Action *m_nextPageAction; - - TikzPreviewMessageWidget *m_infoWidget; - - Poppler::Document *m_tikzPdfDoc; - int m_currentPage; - qreal m_zoomFactor; - qreal m_oldZoomFactor; - bool m_hasZoomed; - - bool m_showCoordinates; - QList m_tikzCoordinates; - int m_precision; + void createInformationLabel(); + void createActions(); + void showPdfPage(); + void centerInfoLabel(); + void setInfoLabelText(const QString &message, + TikzPreviewMessageWidget::PixmapVisibility pixmapVisibility = + TikzPreviewMessageWidget::PixmapNotVisible); + + QGraphicsScene *m_tikzScene; + QGraphicsPixmapItem *m_tikzPixmapItem; + TikzPreviewRenderer *m_tikzPreviewRenderer; + bool m_processRunning; + + QAction *m_zoomInAction; + QAction *m_zoomOutAction; + ZoomAction *m_zoomToAction; + QAction *m_pageSeparator; + Action *m_previousPageAction; + Action *m_nextPageAction; + + TikzPreviewMessageWidget *m_infoWidget; + + Poppler::Document *m_tikzPdfDoc; + int m_currentPage; + qreal m_zoomFactor; + qreal m_oldZoomFactor; + bool m_hasZoomed; + + bool m_showCoordinates; + QList m_tikzCoordinates; + int m_precision; }; #endif diff --git a/common/tikzpreviewcontroller.cpp b/common/tikzpreviewcontroller.cpp index 70d6cd8..db9c515 100644 --- a/common/tikzpreviewcontroller.cpp +++ b/common/tikzpreviewcontroller.cpp @@ -21,7 +21,7 @@ #include "tikzpreviewcontroller.h" #ifndef KTIKZ_USE_KDE -#include +# include #endif #include @@ -50,198 +50,216 @@ static const int s_minUpdateInterval = 1000; // 1 sec TikzPreviewController::TikzPreviewController(MainWidget *mainWidget) { - m_mainWidget = mainWidget; - m_parentWidget = m_mainWidget->widget(); - - m_templateWidget = new TemplateWidget(m_parentWidget); - - m_tikzPreview = new TikzPreview(m_parentWidget); - m_tikzPreviewGenerator = new TikzPreviewGenerator(this); - - createActions(); - - qRegisterMetaType >("QList"); - connect(m_tikzPreviewGenerator, SIGNAL(pixmapUpdated(Poppler::Document*,QList)), - m_tikzPreview, SLOT(pixmapUpdated(Poppler::Document*,QList))); - connect(m_tikzPreviewGenerator, SIGNAL(showErrorMessage(QString)), - m_tikzPreview, SLOT(showErrorMessage(QString))); - connect(m_tikzPreviewGenerator, SIGNAL(setExportActionsEnabled(bool)), - this, SLOT(setExportActionsEnabled(bool))); - connect(m_tikzPreviewGenerator, SIGNAL(updateLog(QString,bool)), - this, SIGNAL(updateLog(QString,bool))); - connect(m_tikzPreviewGenerator, SIGNAL(appendLog(QString,bool)), - this, SIGNAL(appendLog(QString,bool))); - connect(m_templateWidget, SIGNAL(fileNameChanged(QString)), - this, SLOT(setTemplateFileAndRegenerate(QString))); - connect(m_tikzPreview, SIGNAL(showMouseCoordinates(qreal,qreal,int,int)), - this, SIGNAL(showMouseCoordinates(qreal,qreal,int,int))); - - m_regenerateTimer = new QTimer(this); - m_regenerateTimer->setSingleShot(true); - connect(m_regenerateTimer, SIGNAL(timeout()), - this, SLOT(regeneratePreview())); - - m_tempDir = new TempDir(); - m_tikzPreviewGenerator->setTikzFileBaseName(tempFileBaseName()); + m_mainWidget = mainWidget; + m_parentWidget = m_mainWidget->widget(); + + m_templateWidget = new TemplateWidget(m_parentWidget); + + m_tikzPreview = new TikzPreview(m_parentWidget); + m_tikzPreviewGenerator = new TikzPreviewGenerator(this); + + createActions(); + + qRegisterMetaType>("QList"); + connect(m_tikzPreviewGenerator, SIGNAL(pixmapUpdated(Poppler::Document *, QList)), + m_tikzPreview, SLOT(pixmapUpdated(Poppler::Document *, QList))); + connect(m_tikzPreviewGenerator, SIGNAL(showErrorMessage(QString)), m_tikzPreview, + SLOT(showErrorMessage(QString))); + connect(m_tikzPreviewGenerator, SIGNAL(setExportActionsEnabled(bool)), this, + SLOT(setExportActionsEnabled(bool))); + connect(m_tikzPreviewGenerator, SIGNAL(updateLog(QString, bool)), this, + SIGNAL(updateLog(QString, bool))); + connect(m_tikzPreviewGenerator, SIGNAL(appendLog(QString, bool)), this, + SIGNAL(appendLog(QString, bool))); + connect(m_templateWidget, SIGNAL(fileNameChanged(QString)), this, + SLOT(setTemplateFileAndRegenerate(QString))); + connect(m_tikzPreview, SIGNAL(showMouseCoordinates(qreal, qreal, int, int)), this, + SIGNAL(showMouseCoordinates(qreal, qreal, int, int))); + + m_regenerateTimer = new QTimer(this); + m_regenerateTimer->setSingleShot(true); + connect(m_regenerateTimer, SIGNAL(timeout()), this, SLOT(regeneratePreview())); + + m_tempDir = new TempDir(); + m_tikzPreviewGenerator->setTikzFileBaseName(tempFileBaseName()); #ifdef KTIKZ_USE_KDE - File::setMainWidget(m_parentWidget); - File::setTempDir(m_tempDir->path()); // this must happen before any object of type File is constructed + File::setMainWidget(m_parentWidget); + File::setTempDir( + m_tempDir->path()); // this must happen before any object of type File is constructed #endif } TikzPreviewController::~TikzPreviewController() { - delete m_tikzPreviewGenerator; - delete m_tempDir; + delete m_tikzPreviewGenerator; + delete m_tempDir; } /***************************************************************************/ -const TextCodecProfile *TikzPreviewController::textCodecProfile() const { - return (TextCodecProfile*) this->m_mainWidget; +const TextCodecProfile *TikzPreviewController::textCodecProfile() const +{ + return (TextCodecProfile *)this->m_mainWidget; } - /***************************************************************************/ const QString TikzPreviewController::tempDir() const { - return m_tempDir->path(); + return m_tempDir->path(); } const QString TikzPreviewController::tempFileBaseName() const { - return m_tempDir->path() + QLatin1String("/temptikzcode"); + return m_tempDir->path() + QLatin1String("/temptikzcode"); } const QString TikzPreviewController::tempDirLocation() const { - return m_tempDir->location(); + return m_tempDir->location(); } /***************************************************************************/ TemplateWidget *TikzPreviewController::templateWidget() const { - return m_templateWidget; + return m_templateWidget; } TikzPreview *TikzPreviewController::tikzPreview() const { - return m_tikzPreview; + return m_tikzPreview; } /***************************************************************************/ void TikzPreviewController::createActions() { - // File - m_exportAction = new Action(Icon(QLatin1String("document-export")), tr("E&xport"), m_parentWidget, QLatin1String("file_export_as")); - m_exportAction->setStatusTip(tr("Export image to various formats")); - m_exportAction->setWhatsThis(tr("

Export image to various formats.

")); - QMenu *exportMenu = new QMenu(m_parentWidget); - m_exportAction->setMenu(exportMenu); - - Action *exportEpsAction = new Action(Icon(QLatin1String("image-x-eps")), tr("&Encapsulated PostScript (EPS)"), exportMenu, QLatin1String("file_export_eps")); - exportEpsAction->setData(QLatin1String("image/x-eps")); - exportEpsAction->setStatusTip(tr("Export to EPS")); - exportEpsAction->setWhatsThis(tr("

Export to EPS.

")); - connect(exportEpsAction, SIGNAL(triggered()), this, SLOT(exportImage())); - exportMenu->addAction(exportEpsAction); - - Action *exportPdfAction = new Action(Icon(QLatin1String("application-pdf")), tr("&Portable Document Format (PDF)"), exportMenu, QLatin1String("file_export_pdf")); - exportPdfAction->setData(QLatin1String("application/pdf")); - exportPdfAction->setStatusTip(tr("Export to PDF")); - exportPdfAction->setWhatsThis(tr("

Export to PDF.

")); - connect(exportPdfAction, SIGNAL(triggered()), this, SLOT(exportImage())); - exportMenu->addAction(exportPdfAction); - - QStringList mimeTypes; - QStringList mimeTypeNames; - mimeTypes << QLatin1String("png") << QLatin1String("jpeg") << QLatin1String("tiff") << QLatin1String("bmp"); - mimeTypeNames << tr("Portable Network &Graphics") << tr("&Joint Photographic Experts Group Format") << tr("&Tagged Image File Format") << tr("&Windows Bitmap"); - for (int i = 0; i < mimeTypes.size(); ++i) - { - Action *exportImageAction = new Action(Icon(QLatin1String("image-") + mimeTypes.at(i)), mimeTypeNames.at(i) + QLatin1String(" (") + mimeTypes.at(i).toUpper() + QLatin1Char(')'), exportMenu, QLatin1String("file_export_") + mimeTypes.at(i)); - exportImageAction->setData(QLatin1String("image/") + mimeTypes.at(i)); - exportImageAction->setStatusTip(tr("Export to %1").arg(mimeTypes.at(i).toUpper())); - exportImageAction->setWhatsThis(tr("

Export to %1.

").arg(mimeTypes.at(i).toUpper())); - connect(exportImageAction, SIGNAL(triggered()), this, SLOT(exportImage())); - exportMenu->addAction(exportImageAction); - } + // File + m_exportAction = new Action(Icon(QLatin1String("document-export")), tr("E&xport"), + m_parentWidget, QLatin1String("file_export_as")); + m_exportAction->setStatusTip(tr("Export image to various formats")); + m_exportAction->setWhatsThis(tr("

Export image to various formats.

")); + QMenu *exportMenu = new QMenu(m_parentWidget); + m_exportAction->setMenu(exportMenu); + + Action *exportEpsAction = + new Action(Icon(QLatin1String("image-x-eps")), tr("&Encapsulated PostScript (EPS)"), + exportMenu, QLatin1String("file_export_eps")); + exportEpsAction->setData(QLatin1String("image/x-eps")); + exportEpsAction->setStatusTip(tr("Export to EPS")); + exportEpsAction->setWhatsThis(tr("

Export to EPS.

")); + connect(exportEpsAction, SIGNAL(triggered()), this, SLOT(exportImage())); + exportMenu->addAction(exportEpsAction); + + Action *exportPdfAction = new Action(Icon(QLatin1String("application-pdf")), + tr("&Portable Document Format (PDF)"), exportMenu, + QLatin1String("file_export_pdf")); + exportPdfAction->setData(QLatin1String("application/pdf")); + exportPdfAction->setStatusTip(tr("Export to PDF")); + exportPdfAction->setWhatsThis(tr("

Export to PDF.

")); + connect(exportPdfAction, SIGNAL(triggered()), this, SLOT(exportImage())); + exportMenu->addAction(exportPdfAction); + + QStringList mimeTypes; + QStringList mimeTypeNames; + mimeTypes << QLatin1String("png") << QLatin1String("jpeg") << QLatin1String("tiff") + << QLatin1String("bmp"); + mimeTypeNames << tr("Portable Network &Graphics") + << tr("&Joint Photographic Experts Group Format") + << tr("&Tagged Image File Format") << tr("&Windows Bitmap"); + for (int i = 0; i < mimeTypes.size(); ++i) { + Action *exportImageAction = + new Action(Icon(QLatin1String("image-") + mimeTypes.at(i)), + mimeTypeNames.at(i) + QLatin1String(" (") + mimeTypes.at(i).toUpper() + + QLatin1Char(')'), + exportMenu, QLatin1String("file_export_") + mimeTypes.at(i)); + exportImageAction->setData(QLatin1String("image/") + mimeTypes.at(i)); + exportImageAction->setStatusTip(tr("Export to %1").arg(mimeTypes.at(i).toUpper())); + exportImageAction->setWhatsThis(tr("

Export to %1.

").arg(mimeTypes.at(i).toUpper())); + connect(exportImageAction, SIGNAL(triggered()), this, SLOT(exportImage())); + exportMenu->addAction(exportImageAction); + } #ifndef KTIKZ_KPART // don't have two "Print" actions in the kpart - m_printPreviewAction = StandardAction::printPreview(this, SLOT(printPreviewImage()), this); - m_printPreviewAction->setStatusTip(tr("Print preview image")); - m_printPreviewAction->setWhatsThis(tr("

Show print preview of the preview image.

")); + m_printPreviewAction = StandardAction::printPreview(this, SLOT(printPreviewImage()), this); + m_printPreviewAction->setStatusTip(tr("Print preview image")); + m_printPreviewAction->setWhatsThis(tr("

Show print preview of the preview image.

")); - m_printAction = StandardAction::print(this, SLOT(printImage()), this); - m_printAction->setStatusTip(tr("Print image")); - m_printAction->setWhatsThis(tr("

Print the preview image.

")); + m_printAction = StandardAction::print(this, SLOT(printImage()), this); + m_printAction->setStatusTip(tr("Print image")); + m_printAction->setWhatsThis(tr("

Print the preview image.

")); #endif - setExportActionsEnabled(false); - - // View - m_procStopAction = new Action(Icon(QLatin1String("process-stop")), tr("&Stop Process"), m_parentWidget, QLatin1String("stop_process")); - m_procStopAction->setShortcut(tr("Escape", "View|Stop Process")); - m_procStopAction->setStatusTip(tr("Abort current process")); - m_procStopAction->setWhatsThis(tr("

Abort the execution of the currently running process.

")); - m_procStopAction->setEnabled(false); - connect(m_procStopAction, SIGNAL(triggered()), this, SLOT(abortProcess())); - - m_shellEscapeAction = new ToggleAction(Icon(QLatin1String("application-x-executable")), tr("S&hell Escape"), m_parentWidget, QLatin1String("shell_escape")); - m_shellEscapeAction->setStatusTip(tr("Enable the \\write18{shell-command} feature")); - m_shellEscapeAction->setWhatsThis(tr("

Enable LaTeX to run shell commands, this is needed when you want to plot functions using gnuplot within TikZ." - "

Warning: Enabling this may cause malicious software to be run on your computer! Check the LaTeX code to see which commands are executed.

")); - connect(m_shellEscapeAction, SIGNAL(toggled(bool)), this, SLOT(toggleShellEscaping(bool))); - - connect(m_tikzPreviewGenerator, SIGNAL(processRunning(bool)), - this, SLOT(setProcessRunning(bool))); + setExportActionsEnabled(false); + + // View + m_procStopAction = new Action(Icon(QLatin1String("process-stop")), tr("&Stop Process"), + m_parentWidget, QLatin1String("stop_process")); + m_procStopAction->setShortcut(tr("Escape", "View|Stop Process")); + m_procStopAction->setStatusTip(tr("Abort current process")); + m_procStopAction->setWhatsThis( + tr("

Abort the execution of the currently running process.

")); + m_procStopAction->setEnabled(false); + connect(m_procStopAction, SIGNAL(triggered()), this, SLOT(abortProcess())); + + m_shellEscapeAction = + new ToggleAction(Icon(QLatin1String("application-x-executable")), tr("S&hell Escape"), + m_parentWidget, QLatin1String("shell_escape")); + m_shellEscapeAction->setStatusTip(tr("Enable the \\write18{shell-command} feature")); + m_shellEscapeAction->setWhatsThis(tr( + "

Enable LaTeX to run shell commands, this is needed when you want to plot functions " + "using gnuplot within TikZ." + "

Warning: Enabling this may cause malicious software to be run " + "on your computer! Check the LaTeX code to see which commands are executed.

")); + connect(m_shellEscapeAction, SIGNAL(toggled(bool)), this, SLOT(toggleShellEscaping(bool))); + + connect(m_tikzPreviewGenerator, SIGNAL(processRunning(bool)), this, + SLOT(setProcessRunning(bool))); } #ifndef KTIKZ_USE_KDE QAction *TikzPreviewController::exportAction() { - return m_exportAction; + return m_exportAction; } QAction *TikzPreviewController::printPreviewAction() { - return m_printPreviewAction; + return m_printPreviewAction; } QAction *TikzPreviewController::printAction() { - return m_printAction; + return m_printAction; } QMenu *TikzPreviewController::menu() { - QMenu *viewMenu = new QMenu(tr("&View"), m_parentWidget); - viewMenu->addActions(m_tikzPreview->actions()); - viewMenu->addSeparator(); - viewMenu->addAction(m_procStopAction); - viewMenu->addAction(m_shellEscapeAction); - return viewMenu; + QMenu *viewMenu = new QMenu(tr("&View"), m_parentWidget); + viewMenu->addActions(m_tikzPreview->actions()); + viewMenu->addSeparator(); + viewMenu->addAction(m_procStopAction); + viewMenu->addAction(m_shellEscapeAction); + return viewMenu; } -QList TikzPreviewController::toolBars() +QList TikzPreviewController::toolBars() { - QToolBar *toolBar = new QToolBar(tr("Run"), m_parentWidget); - toolBar->setObjectName(QLatin1String("RunToolBar")); - toolBar->addAction(m_procStopAction); - toolBar->addAction(m_shellEscapeAction); + QToolBar *toolBar = new QToolBar(tr("Run"), m_parentWidget); + toolBar->setObjectName(QLatin1String("RunToolBar")); + toolBar->addAction(m_procStopAction); + toolBar->addAction(m_shellEscapeAction); - m_toolBars << m_tikzPreview->toolBar() << toolBar; + m_toolBars << m_tikzPreview->toolBar() << toolBar; - return m_toolBars; + return m_toolBars; } void TikzPreviewController::setToolBarStyle(const Qt::ToolButtonStyle &style) { - for (int i = 0; i < m_toolBars.size(); ++i) - m_toolBars.at(i)->setToolButtonStyle(style); + for (int i = 0; i < m_toolBars.size(); ++i) + m_toolBars.at(i)->setToolButtonStyle(style); } #endif @@ -249,295 +267,307 @@ void TikzPreviewController::setToolBarStyle(const Qt::ToolButtonStyle &style) Url TikzPreviewController::getExportUrl(const Url &url, const QString &mimeType) const { - QString currentFile; - const QString extension = mimeType == QLatin1String("image/x-eps") ? QLatin1String("eps") - : (mimeType == QLatin1String("application/pdf") ? QLatin1String("pdf") : mimeType.mid(6)); - if (!url.isEmpty()) - { - const QFileInfo currentFileInfo(url.path()); - currentFile = currentFileInfo.absolutePath(); - if (!currentFile.endsWith(QLatin1Char('/'))) - currentFile += QLatin1Char('/'); - currentFile += currentFileInfo.completeBaseName() - + (m_tikzPreview->numberOfPages() > 1 && mimeType != QLatin1String("application/pdf") ? QLatin1String("_") + QString::number(m_tikzPreview->currentPage() + 1) : QString()) - + QLatin1Char('.') + extension; - } - return FileDialog::getSaveUrl(m_parentWidget, tr("Export image"), Url(currentFile), mimeType); + QString currentFile; + const QString extension = mimeType == QLatin1String("image/x-eps") + ? QLatin1String("eps") + : (mimeType == QLatin1String("application/pdf") ? QLatin1String("pdf") + : mimeType.mid(6)); + if (!url.isEmpty()) { + const QFileInfo currentFileInfo(url.path()); + currentFile = currentFileInfo.absolutePath(); + if (!currentFile.endsWith(QLatin1Char('/'))) + currentFile += QLatin1Char('/'); + currentFile += currentFileInfo.completeBaseName() + + (m_tikzPreview->numberOfPages() > 1 + && mimeType != QLatin1String("application/pdf") + ? QLatin1String("_") + QString::number(m_tikzPreview->currentPage() + 1) + : QString()) + + QLatin1Char('.') + extension; + } + return FileDialog::getSaveUrl(m_parentWidget, tr("Export image"), Url(currentFile), mimeType); } void TikzPreviewController::exportImage() { - QAction *action = qobject_cast(sender()); - const QString mimeType = action->data().toString(); - - const QPixmap tikzImage = m_tikzPreview->pixmap(); - if (tikzImage.isNull()) - return; - - const Url exportUrl = getExportUrl(m_mainWidget->url(), mimeType); - if (!exportUrl.isValid()) - return; - - QString extension; - if (mimeType == QLatin1String("application/pdf")) - { - extension = QLatin1String(".pdf"); - } - else if (mimeType == QLatin1String("image/x-eps")) - { - if (!m_tikzPreviewGenerator->generateEpsFile(m_tikzPreview->currentPage())) - { - MessageBox::error(m_parentWidget, tr("Export failed."), QCoreApplication::applicationName()); - return; - } - extension = QLatin1String(".eps"); - } - else - { - extension = QLatin1Char('.') + mimeType.mid(6); - if (!tikzImage.save(tempFileBaseName() + extension)) - { - MessageBox::error(m_parentWidget, tr("Export failed."), QCoreApplication::applicationName()); - return; - } - } - - if (!File::copy(Url(tempFileBaseName() + extension), exportUrl)) - MessageBox::error(m_parentWidget, - tr("The image could not be exported to the file \"%1\".").arg(exportUrl.path()), - QCoreApplication::applicationName()); + QAction *action = qobject_cast(sender()); + const QString mimeType = action->data().toString(); + + const QPixmap tikzImage = m_tikzPreview->pixmap(); + if (tikzImage.isNull()) + return; + + const Url exportUrl = getExportUrl(m_mainWidget->url(), mimeType); + if (!exportUrl.isValid()) + return; + + QString extension; + if (mimeType == QLatin1String("application/pdf")) { + extension = QLatin1String(".pdf"); + } else if (mimeType == QLatin1String("image/x-eps")) { + if (!m_tikzPreviewGenerator->generateEpsFile(m_tikzPreview->currentPage())) { + MessageBox::error(m_parentWidget, tr("Export failed."), + QCoreApplication::applicationName()); + return; + } + extension = QLatin1String(".eps"); + } else { + extension = QLatin1Char('.') + mimeType.mid(6); + if (!tikzImage.save(tempFileBaseName() + extension)) { + MessageBox::error(m_parentWidget, tr("Export failed."), + QCoreApplication::applicationName()); + return; + } + } + + if (!File::copy(Url(tempFileBaseName() + extension), exportUrl)) + MessageBox::error( + m_parentWidget, + tr("The image could not be exported to the file \"%1\".").arg(exportUrl.path()), + QCoreApplication::applicationName()); } /***************************************************************************/ void TikzPreviewController::printImage(QPrinter *printer) { - // get page range - int startPage, endPage; - if (printer->printRange() == QPrinter::PageRange) - { - startPage = printer->fromPage() - 1; - endPage = printer->toPage() - 1; - } - else if (printer->printRange() == QPrinter::CurrentPage) - { - startPage = m_tikzPreview->currentPage(); - endPage = m_tikzPreview->currentPage(); - } - else - { - startPage = 0; - endPage = m_tikzPreview->numberOfPages() - 1; - } - - // print - QPainter painter; - painter.begin(printer); -// painter.drawPixmap(0, 0, m_tikzPreview->pixmap()); - for (int i = startPage; i <= endPage; ++i) - { - if (i != startPage) - printer->newPage(); - const QImage image = m_tikzPreview->renderToImage(printer->physicalDpiX(), printer->physicalDpiY(), i); - if (!image.isNull()) - { - const double scaleFactor = qMin(double(painter.window().width()) / image.width(), double(painter.window().height()) / image.height()); - painter.drawImage(QRect(0, 0, image.width() * scaleFactor, image.height() * scaleFactor), image, image.rect()); - } - } - painter.end(); + // get page range + int startPage, endPage; + if (printer->printRange() == QPrinter::PageRange) { + startPage = printer->fromPage() - 1; + endPage = printer->toPage() - 1; + } else if (printer->printRange() == QPrinter::CurrentPage) { + startPage = m_tikzPreview->currentPage(); + endPage = m_tikzPreview->currentPage(); + } else { + startPage = 0; + endPage = m_tikzPreview->numberOfPages() - 1; + } + + // print + QPainter painter; + painter.begin(printer); + // painter.drawPixmap(0, 0, m_tikzPreview->pixmap()); + for (int i = startPage; i <= endPage; ++i) { + if (i != startPage) + printer->newPage(); + const QImage image = + m_tikzPreview->renderToImage(printer->physicalDpiX(), printer->physicalDpiY(), i); + if (!image.isNull()) { + const double scaleFactor = qMin(double(painter.window().width()) / image.width(), + double(painter.window().height()) / image.height()); + painter.drawImage( + QRect(0, 0, image.width() * scaleFactor, image.height() * scaleFactor), image, + image.rect()); + } + } + painter.end(); } void TikzPreviewController::printPreviewImage() { - QPrinter printer; - - // choose printer - QPointer printDialog = new QPrintDialog(&printer, m_parentWidget); - printDialog->setWindowTitle(tr("Print preview of image")); - printDialog->setOptions(printDialog->options() | QAbstractPrintDialog::PrintPageRange | QAbstractPrintDialog::PrintCurrentPage); - printDialog->setMinMax(0, m_tikzPreview->numberOfPages()); - QList dialogButtonBoxes = printDialog->findChildren(); - QPushButton *printButton = dialogButtonBoxes.at(0)->button(QDialogButtonBox::Ok); - printButton->setText(tr("Print &preview")); - if (printDialog->exec() != QDialog::Accepted) - { - delete printDialog; - return; - } - delete printDialog; - - // show print preview - PrintPreviewDialog preview(&printer); - connect(&preview, SIGNAL(paintRequested(QPrinter*)), this, SLOT(printImage(QPrinter*))); - preview.exec(); + QPrinter printer; + + // choose printer + QPointer printDialog = new QPrintDialog(&printer, m_parentWidget); + printDialog->setWindowTitle(tr("Print preview of image")); + printDialog->setOptions(printDialog->options() | QAbstractPrintDialog::PrintPageRange + | QAbstractPrintDialog::PrintCurrentPage); + printDialog->setMinMax(0, m_tikzPreview->numberOfPages()); + QList dialogButtonBoxes = printDialog->findChildren(); + QPushButton *printButton = dialogButtonBoxes.at(0)->button(QDialogButtonBox::Ok); + printButton->setText(tr("Print &preview")); + if (printDialog->exec() != QDialog::Accepted) { + delete printDialog; + return; + } + delete printDialog; + + // show print preview + PrintPreviewDialog preview(&printer); + connect(&preview, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printImage(QPrinter *))); + preview.exec(); } void TikzPreviewController::printImage() { - QPrinter printer(QPrinter::PrinterResolution); + QPrinter printer(QPrinter::PrinterResolution); - // choose printer - QPointer printDialog = new QPrintDialog(&printer, m_parentWidget); - printDialog->setWindowTitle(tr("Print image")); - printDialog->setOptions(printDialog->options() | QAbstractPrintDialog::PrintPageRange | QAbstractPrintDialog::PrintCurrentPage); - printDialog->setMinMax(0, m_tikzPreview->numberOfPages()); - if (printDialog->exec() != QDialog::Accepted) - { - delete printDialog; - return; - } - delete printDialog; + // choose printer + QPointer printDialog = new QPrintDialog(&printer, m_parentWidget); + printDialog->setWindowTitle(tr("Print image")); + printDialog->setOptions(printDialog->options() | QAbstractPrintDialog::PrintPageRange + | QAbstractPrintDialog::PrintCurrentPage); + printDialog->setMinMax(0, m_tikzPreview->numberOfPages()); + if (printDialog->exec() != QDialog::Accepted) { + delete printDialog; + return; + } + delete printDialog; - printImage(&printer); + printImage(&printer); } /***************************************************************************/ bool TikzPreviewController::setTemplateFile(const QString &path) { - File templateFile(path, File::ReadOnly); - if (templateFile.file()->exists()) // use local copy of template file if template file is remote - m_tikzPreviewGenerator->setTemplateFile(templateFile.file()->fileName()); - else - m_tikzPreviewGenerator->setTemplateFile(QString()); - return true; + File templateFile(path, File::ReadOnly); + if (templateFile.file()->exists()) // use local copy of template file if template file is remote + m_tikzPreviewGenerator->setTemplateFile(templateFile.file()->fileName()); + else + m_tikzPreviewGenerator->setTemplateFile(QString()); + return true; } void TikzPreviewController::setTemplateFileAndRegenerate(const QString &path) { - if (setTemplateFile(path)) - generatePreview(TikzPreviewGenerator::ReloadTemplate); + if (setTemplateFile(path)) + generatePreview(TikzPreviewGenerator::ReloadTemplate); } void TikzPreviewController::setReplaceTextAndRegenerate(const QString &replace) { - m_tikzPreviewGenerator->setReplaceText(replace); - generatePreview(TikzPreviewGenerator::ReloadTemplate); + m_tikzPreviewGenerator->setReplaceText(replace); + generatePreview(TikzPreviewGenerator::ReloadTemplate); } /***************************************************************************/ QString TikzPreviewController::tikzCode() const { - return m_mainWidget->tikzCode(); + return m_mainWidget->tikzCode(); } QString TikzPreviewController::getLogText() { - return m_tikzPreviewGenerator->getLogText(); + return m_tikzPreviewGenerator->getLogText(); } void TikzPreviewController::generatePreview() { - generatePreview(TikzPreviewGenerator::ReloadTemplate); + generatePreview(TikzPreviewGenerator::ReloadTemplate); } void TikzPreviewController::generatePreview(TikzPreviewGenerator::TemplateStatus templateStatus) { - if (templateStatus == TikzPreviewGenerator::ReloadTemplate) // old aux files may contain commands available in the old template, but not anymore in the new template - m_tempDir->cleanUp(); - - // the directory in which the pgf file is located is added to TEXINPUTS (and the directory of the old pgf file is removed) before running latex - const QString currentFileName = m_mainWidget->url().path(); - if (!m_currentFileName.isEmpty() && currentFileName != m_currentFileName) - m_tikzPreviewGenerator->removeFromLatexSearchPath(QFileInfo(m_currentFileName).absolutePath()); - m_currentFileName = currentFileName; - if (!currentFileName.isEmpty()) - m_tikzPreviewGenerator->addToLatexSearchPath(QFileInfo(currentFileName).absolutePath()); - - m_tikzPreviewGenerator->abortProcess(); // abort still running process before starting a new one (without this, if a process hangs, all subsequently started processes are executed one after the other when the user aborts the hanging process) - m_tikzPreviewGenerator->generatePreview(templateStatus); + if (templateStatus + == TikzPreviewGenerator::ReloadTemplate) // old aux files may contain commands available in + // the old template, but not anymore in the new + // template + m_tempDir->cleanUp(); + + // the directory in which the pgf file is located is added to TEXINPUTS (and the directory of + // the old pgf file is removed) before running latex + const QString currentFileName = m_mainWidget->url().path(); + if (!m_currentFileName.isEmpty() && currentFileName != m_currentFileName) + m_tikzPreviewGenerator->removeFromLatexSearchPath( + QFileInfo(m_currentFileName).absolutePath()); + m_currentFileName = currentFileName; + if (!currentFileName.isEmpty()) + m_tikzPreviewGenerator->addToLatexSearchPath(QFileInfo(currentFileName).absolutePath()); + + m_tikzPreviewGenerator->abortProcess(); // abort still running process before starting a new one + // (without this, if a process hangs, all subsequently + // started processes are executed one after the other + // when the user aborts the hanging process) + m_tikzPreviewGenerator->generatePreview(templateStatus); } void TikzPreviewController::regeneratePreview() { - generatePreview(TikzPreviewGenerator::DontReloadTemplate); + generatePreview(TikzPreviewGenerator::DontReloadTemplate); } void TikzPreviewController::regeneratePreviewAfterDelay() { - if (tikzCode().isEmpty()) - { - m_tikzPreview->pixmapUpdated(0); // clean up error messages in preview - Q_EMIT updateLog(QString(), false); // clean up error messages in log panel - } - // Each start cancels the previous one, this means that timeout() is only - // fired when there have been no changes in the text editor for the last - // s_minUpdateInterval msecs. This ensures that the preview is not - // regenerated on every character that is added/changed/removed. - m_regenerateTimer->start(s_minUpdateInterval); + if (tikzCode().isEmpty()) { + m_tikzPreview->pixmapUpdated(0); // clean up error messages in preview + Q_EMIT updateLog(QString(), false); // clean up error messages in log panel + } + // Each start cancels the previous one, this means that timeout() is only + // fired when there have been no changes in the text editor for the last + // s_minUpdateInterval msecs. This ensures that the preview is not + // regenerated on every character that is added/changed/removed. + m_regenerateTimer->start(s_minUpdateInterval); } void TikzPreviewController::emptyPreview() { - setExportActionsEnabled(false); - m_tikzPreviewGenerator->abortProcess(); // abort still running processes - m_tikzPreview->emptyPreview(); + setExportActionsEnabled(false); + m_tikzPreviewGenerator->abortProcess(); // abort still running processes + m_tikzPreview->emptyPreview(); } void TikzPreviewController::abortProcess() { - // We cannot connect the triggered signal of m_procStopAction directly - // to m_tikzPreviewGenerator->abortProcess() because then the latter would - // be run in the same thread as the process which must be aborted, so the - // abortion would be executed after the process finishes. So we must abort - // the process in the main thread by calling m_tikzPreviewGenerator->abortProcess() - // as a regular (non-slot) function. - m_tikzPreviewGenerator->abortProcess(); + // We cannot connect the triggered signal of m_procStopAction directly + // to m_tikzPreviewGenerator->abortProcess() because then the latter would + // be run in the same thread as the process which must be aborted, so the + // abortion would be executed after the process finishes. So we must abort + // the process in the main thread by calling m_tikzPreviewGenerator->abortProcess() + // as a regular (non-slot) function. + m_tikzPreviewGenerator->abortProcess(); } /***************************************************************************/ void TikzPreviewController::applySettings() { - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - m_tikzPreviewGenerator->setLatexCommand(settings.value(QLatin1String("LatexCommand"), QLatin1String("pdflatex")).toString()); - m_tikzPreviewGenerator->setPdftopsCommand(settings.value(QLatin1String("PdftopsCommand"), QLatin1String("pdftops")).toString()); - const bool useShellEscaping = settings.value(QLatin1String("UseShellEscaping"), false).toBool(); - - disconnect(m_shellEscapeAction, SIGNAL(toggled(bool)), this, SLOT(toggleShellEscaping(bool))); - m_shellEscapeAction->setChecked(useShellEscaping); - m_tikzPreviewGenerator->setShellEscaping(useShellEscaping); - connect(m_shellEscapeAction, SIGNAL(toggled(bool)), this, SLOT(toggleShellEscaping(bool))); - - setTemplateFile(settings.value(QLatin1String("TemplateFile")).toString()); - const QString replaceText = settings.value(QLatin1String("TemplateReplaceText"), QLatin1String("<>")).toString(); - m_tikzPreviewGenerator->setReplaceText(replaceText); - m_templateWidget->setReplaceText(replaceText); - m_templateWidget->setEditor(settings.value(QLatin1String("TemplateEditor"), QLatin1String("")).toString()); - - settings.beginGroup(QLatin1String("Preview")); - m_tikzPreview->setShowCoordinates(settings.value(QLatin1String("ShowCoordinates"), true).toBool()); - m_tikzPreview->setCoordinatePrecision(settings.value(QLatin1String("ShowCoordinatesPrecision"), -1).toInt()); - m_tikzPreview->setBackgroundColor(settings.value(QLatin1String("PreviewBackgroundColor"), QColor(0, 0, 0)).value()); - settings.endGroup(); + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + m_tikzPreviewGenerator->setLatexCommand( + settings.value(QLatin1String("LatexCommand"), QLatin1String("pdflatex")).toString()); + m_tikzPreviewGenerator->setPdftopsCommand( + settings.value(QLatin1String("PdftopsCommand"), QLatin1String("pdftops")).toString()); + const bool useShellEscaping = settings.value(QLatin1String("UseShellEscaping"), false).toBool(); + + disconnect(m_shellEscapeAction, SIGNAL(toggled(bool)), this, SLOT(toggleShellEscaping(bool))); + m_shellEscapeAction->setChecked(useShellEscaping); + m_tikzPreviewGenerator->setShellEscaping(useShellEscaping); + connect(m_shellEscapeAction, SIGNAL(toggled(bool)), this, SLOT(toggleShellEscaping(bool))); + + setTemplateFile(settings.value(QLatin1String("TemplateFile")).toString()); + const QString replaceText = + settings.value(QLatin1String("TemplateReplaceText"), QLatin1String("<>")).toString(); + m_tikzPreviewGenerator->setReplaceText(replaceText); + m_templateWidget->setReplaceText(replaceText); + m_templateWidget->setEditor( + settings.value(QLatin1String("TemplateEditor"), QLatin1String("")).toString()); + + settings.beginGroup(QLatin1String("Preview")); + m_tikzPreview->setShowCoordinates( + settings.value(QLatin1String("ShowCoordinates"), true).toBool()); + m_tikzPreview->setCoordinatePrecision( + settings.value(QLatin1String("ShowCoordinatesPrecision"), -1).toInt()); + m_tikzPreview->setBackgroundColor( + settings.value(QLatin1String("PreviewBackgroundColor"), QColor(0, 0, 0)) + .value()); + settings.endGroup(); } void TikzPreviewController::setExportActionsEnabled(bool enabled) { - m_exportAction->setEnabled(enabled); + m_exportAction->setEnabled(enabled); #ifndef KTIKZ_KPART - m_printPreviewAction->setEnabled(enabled); - m_printAction->setEnabled(enabled); + m_printPreviewAction->setEnabled(enabled); + m_printAction->setEnabled(enabled); #endif } void TikzPreviewController::setProcessRunning(bool isRunning) { - m_procStopAction->setEnabled(isRunning); - if (isRunning) - QApplication::setOverrideCursor(Qt::BusyCursor); - else - QApplication::restoreOverrideCursor(); - m_tikzPreview->setProcessRunning(isRunning); + m_procStopAction->setEnabled(isRunning); + if (isRunning) + QApplication::setOverrideCursor(Qt::BusyCursor); + else + QApplication::restoreOverrideCursor(); + m_tikzPreview->setProcessRunning(isRunning); } void TikzPreviewController::toggleShellEscaping(bool useShellEscaping) { - QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); - settings.setValue(QLatin1String("UseShellEscaping"), useShellEscaping); + QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); + settings.setValue(QLatin1String("UseShellEscaping"), useShellEscaping); - m_tikzPreviewGenerator->setShellEscaping(useShellEscaping); - generatePreview(TikzPreviewGenerator::DontReloadTemplate); + m_tikzPreviewGenerator->setShellEscaping(useShellEscaping); + generatePreview(TikzPreviewGenerator::DontReloadTemplate); } diff --git a/common/tikzpreviewcontroller.h b/common/tikzpreviewcontroller.h index 3fde0de..2f3d971 100644 --- a/common/tikzpreviewcontroller.h +++ b/common/tikzpreviewcontroller.h @@ -43,79 +43,79 @@ class ToggleAction; class TikzPreviewController : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit TikzPreviewController(MainWidget *mainWidget); - ~TikzPreviewController(); - - const TextCodecProfile* textCodecProfile() const; - const QString tempDir() const; - const QString tempDirLocation() const; - TemplateWidget *templateWidget() const; - TikzPreview *tikzPreview() const; + explicit TikzPreviewController(MainWidget *mainWidget); + ~TikzPreviewController(); + + const TextCodecProfile *textCodecProfile() const; + const QString tempDir() const; + const QString tempDirLocation() const; + TemplateWidget *templateWidget() const; + TikzPreview *tikzPreview() const; #ifndef KTIKZ_USE_KDE - QAction *exportAction(); - QAction *printPreviewAction(); - QAction *printAction(); - QMenu *menu(); - QList toolBars(); - void setToolBarStyle(const Qt::ToolButtonStyle &style); + QAction *exportAction(); + QAction *printPreviewAction(); + QAction *printAction(); + QMenu *menu(); + QList toolBars(); + void setToolBarStyle(const Qt::ToolButtonStyle &style); #endif - QString tikzCode() const; - QString getLogText(); - void emptyPreview(); - void applySettings(); + QString tikzCode() const; + QString getLogText(); + void emptyPreview(); + void applySettings(); public Q_SLOTS: - void printPreviewImage(); - void printImage(); - void generatePreview(); - void regeneratePreviewAfterDelay(); + void printPreviewImage(); + void printImage(); + void generatePreview(); + void regeneratePreviewAfterDelay(); private Q_SLOTS: - void setTemplateFileAndRegenerate(const QString &path); - void setReplaceTextAndRegenerate(const QString &replace); - void regeneratePreview(); - void abortProcess(); - void exportImage(); - void printImage(QPrinter *printer); - void setExportActionsEnabled(bool enabled); - void setProcessRunning(bool isRunning); - void toggleShellEscaping(bool useShellEscaping); + void setTemplateFileAndRegenerate(const QString &path); + void setReplaceTextAndRegenerate(const QString &replace); + void regeneratePreview(); + void abortProcess(); + void exportImage(); + void printImage(QPrinter *printer); + void setExportActionsEnabled(bool enabled); + void setProcessRunning(bool isRunning); + void toggleShellEscaping(bool useShellEscaping); Q_SIGNALS: - void updateLog(const QString &logText, bool runFailed); - void appendLog(const QString &logText, bool runFailed); - void showMouseCoordinates(qreal x, qreal y, int precisionX, int precisionY); + void updateLog(const QString &logText, bool runFailed); + void appendLog(const QString &logText, bool runFailed); + void showMouseCoordinates(qreal x, qreal y, int precisionX, int precisionY); private: - const QString tempFileBaseName() const; - void createActions(); - void generatePreview(TikzPreviewGenerator::TemplateStatus templateStatus); - bool setTemplateFile(const QString &path); - Url getExportUrl(const Url &url, const QString &mimeType) const; + const QString tempFileBaseName() const; + void createActions(); + void generatePreview(TikzPreviewGenerator::TemplateStatus templateStatus); + bool setTemplateFile(const QString &path); + Url getExportUrl(const Url &url, const QString &mimeType) const; - MainWidget *m_mainWidget; - QWidget *m_parentWidget; + MainWidget *m_mainWidget; + QWidget *m_parentWidget; - TemplateWidget *m_templateWidget; - TikzPreview *m_tikzPreview; - TikzPreviewGenerator *m_tikzPreviewGenerator; + TemplateWidget *m_templateWidget; + TikzPreview *m_tikzPreview; + TikzPreviewGenerator *m_tikzPreviewGenerator; - QTimer *m_regenerateTimer; + QTimer *m_regenerateTimer; #ifndef KTIKZ_USE_KDE - QList m_toolBars; + QList m_toolBars; #endif - Action *m_exportAction; - Action *m_printPreviewAction; - Action *m_printAction; - Action *m_procStopAction; - ToggleAction *m_shellEscapeAction; - - TempDir *m_tempDir; - QString m_currentFileName; + Action *m_exportAction; + Action *m_printPreviewAction; + Action *m_printAction; + Action *m_procStopAction; + ToggleAction *m_shellEscapeAction; + + TempDir *m_tempDir; + QString m_currentFileName; }; #endif diff --git a/common/tikzpreviewgenerator.cpp b/common/tikzpreviewgenerator.cpp index 4e52d26..5b22d73 100644 --- a/common/tikzpreviewgenerator.cpp +++ b/common/tikzpreviewgenerator.cpp @@ -23,7 +23,7 @@ #include "tikzpreviewgenerator.h" #ifdef KTIKZ_USE_KDE -#include +# include #endif #include #include @@ -45,594 +45,607 @@ static const QChar s_pathSeparator = QLatin1Char(':'); #endif TikzPreviewGenerator::TikzPreviewGenerator(TikzPreviewController *parent) - : m_parent(parent) - , m_tikzPdfDoc(0) - , m_process(0) - , m_processAborted(false) - , m_runFailed(false) - , m_firstRun(true) - , m_templateChanged(true) // is set correctly in generatePreviewImpl() - , m_useShellEscaping(false) // is set in setShellEscaping() at startup + : m_parent(parent), + m_tikzPdfDoc(0), + m_process(0), + m_processAborted(false), + m_runFailed(false), + m_firstRun(true), + m_templateChanged(true) // is set correctly in generatePreviewImpl() + , + m_useShellEscaping(false) // is set in setShellEscaping() at startup { - qRegisterMetaType("TemplateStatus"); // needed for Q_ARG below + qRegisterMetaType("TemplateStatus"); // needed for Q_ARG below - m_processEnvironment = QProcessEnvironment::systemEnvironment(); + m_processEnvironment = QProcessEnvironment::systemEnvironment(); - moveToThread(&m_thread); - m_thread.start(); + moveToThread(&m_thread); + m_thread.start(); } TikzPreviewGenerator::~TikzPreviewGenerator() { - // stop the thread before destroying this object - if (m_thread.isRunning()) - { - m_thread.quit(); - m_thread.wait(); - } -// Q_EMIT processRunning(false); // this causes a segmentation fault on exit on Arch Linux - - delete m_tikzPdfDoc; + // stop the thread before destroying this object + if (m_thread.isRunning()) { + m_thread.quit(); + m_thread.wait(); + } + // Q_EMIT processRunning(false); // this causes a segmentation fault on exit on Arch Linux + + delete m_tikzPdfDoc; } /***************************************************************************/ void TikzPreviewGenerator::setTikzFileBaseName(const QString &name) { - const QMutexLocker lock(&m_memberLock); - m_tikzFileBaseName = name; + const QMutexLocker lock(&m_memberLock); + m_tikzFileBaseName = name; } void TikzPreviewGenerator::setLatexCommand(const QString &command) { - const QMutexLocker lock(&m_memberLock); - m_latexCommand = command; + const QMutexLocker lock(&m_memberLock); + m_latexCommand = command; } void TikzPreviewGenerator::setPdftopsCommand(const QString &command) { - const QMutexLocker lock(&m_memberLock); - m_pdftopsCommand = command; + const QMutexLocker lock(&m_memberLock); + m_pdftopsCommand = command; } void TikzPreviewGenerator::setShellEscaping(bool useShellEscaping) { - m_memberLock.lock(); - m_useShellEscaping = useShellEscaping; - m_memberLock.unlock(); - - if (useShellEscaping) - { - QString gnuplotPath = QStandardPaths::findExecutable(QLatin1String("gnuplot")); // search in system path - if (gnuplotPath.isEmpty() || !QFileInfo(gnuplotPath).isExecutable()) // not found - Q_EMIT showErrorMessage(tr("Gnuplot cannot be executed. Either Gnuplot is not installed " - "or it is not available in the system PATH or you may have insufficient " - "permissions to invoke the program.")); - } + m_memberLock.lock(); + m_useShellEscaping = useShellEscaping; + m_memberLock.unlock(); + + if (useShellEscaping) { + QString gnuplotPath = + QStandardPaths::findExecutable(QLatin1String("gnuplot")); // search in system path + if (gnuplotPath.isEmpty() || !QFileInfo(gnuplotPath).isExecutable()) // not found + Q_EMIT showErrorMessage( + tr("Gnuplot cannot be executed. Either Gnuplot is not installed " + "or it is not available in the system PATH or you may have insufficient " + "permissions to invoke the program.")); + } } void TikzPreviewGenerator::setTemplateFile(const QString &fileName) { - m_memberLock.lock(); - const QString oldTemplateFileName = m_templateFileName; - m_templateFileName = fileName; - m_memberLock.unlock(); + m_memberLock.lock(); + const QString oldTemplateFileName = m_templateFileName; + m_templateFileName = fileName; + m_memberLock.unlock(); - if (!oldTemplateFileName.isEmpty()) - removeFromLatexSearchPath(QFileInfo(oldTemplateFileName).absolutePath()); + if (!oldTemplateFileName.isEmpty()) + removeFromLatexSearchPath(QFileInfo(oldTemplateFileName).absolutePath()); - if (!fileName.isEmpty()) - addToLatexSearchPath(QFileInfo(fileName).absolutePath()); + if (!fileName.isEmpty()) + addToLatexSearchPath(QFileInfo(fileName).absolutePath()); } void TikzPreviewGenerator::setReplaceText(const QString &replace) { - const QMutexLocker lock(&m_memberLock); - m_tikzReplaceText = replace; + const QMutexLocker lock(&m_memberLock); + m_tikzReplaceText = replace; } /***************************************************************************/ QString TikzPreviewGenerator::getLogText() const { - const QMutexLocker lock(&m_memberLock); - return m_logText; + const QMutexLocker lock(&m_memberLock); + return m_logText; } static QString getParsedLogText(QTextStream *logStream) { - QString logText; - - QRegExp errorPattern(QLatin1String("(\\S*):(\\d+): (.*$)")); - QList errorMessageList; - errorMessageList << QLatin1String("Undefined control sequence") - << QLatin1String("LaTeX Warning:") << QLatin1String("LaTeX Error:") - << QLatin1String("Runaway argument?") - << QLatin1String("Missing character:") << QLatin1String("Error:"); - - QString logLine; - while (!logStream->atEnd()) - { - logLine = logStream->readLine(); - if (errorPattern.indexIn(logLine) > -1) - { - // show error message and correct line number - QString lineNum = QString::number(errorPattern.cap(2).toInt()); - const QString errorMsg = errorPattern.cap(3); - logText += QLatin1String("[LaTeX] Line ") + lineNum + QLatin1String(": ") + errorMsg; - - // while we don't get a line starting with "l. ...", we have to add the line to the first error message - QRegExp rx(QLatin1String("^l\\.(\\d+)(.*)")); - logLine = logStream->readLine(); - while (rx.indexIn(logLine) < 0 && !logStream->atEnd()) - { - if (logLine.isEmpty()) - logText += QLatin1String("\n[LaTeX] Line ") + lineNum + QLatin1String(": "); - if (!logLine.startsWith(QLatin1String("Type"))) // don't add lines that invite the user to type a command, since we are not in the console - logText += logLine; - logLine = logStream->readLine(); - } - logText += QLatin1Char('\n'); - if (logStream->atEnd()) break; - - // add the line starting with "l. ..." and the next line - lineNum = QString::number(rx.cap(1).toInt() - 7); - logLine = QLatin1String("l.") + lineNum + rx.cap(2); - logText += logLine + QLatin1Char('\n'); - logText += logStream->readLine() + QLatin1Char('\n'); - } - else - { - for (int i = 1; i < errorMessageList.size(); ++i) - { - if (logLine.contains(errorMessageList.at(i))) - { - logText += logLine + QLatin1Char('\n'); - logText += logStream->readLine() + QLatin1Char('\n'); - logText += logStream->readLine() + QLatin1Char('\n'); // we assume that the error message is not displayed on more than 3 lines in the log, so we stop here - break; - } - } - } - } - - return logText; + QString logText; + + QRegExp errorPattern(QLatin1String("(\\S*):(\\d+): (.*$)")); + QList errorMessageList; + errorMessageList << QLatin1String("Undefined control sequence") + << QLatin1String("LaTeX Warning:") << QLatin1String("LaTeX Error:") + << QLatin1String("Runaway argument?") << QLatin1String("Missing character:") + << QLatin1String("Error:"); + + QString logLine; + while (!logStream->atEnd()) { + logLine = logStream->readLine(); + if (errorPattern.indexIn(logLine) > -1) { + // show error message and correct line number + QString lineNum = QString::number(errorPattern.cap(2).toInt()); + const QString errorMsg = errorPattern.cap(3); + logText += QLatin1String("[LaTeX] Line ") + lineNum + QLatin1String(": ") + errorMsg; + + // while we don't get a line starting with "l. ...", we have to add the line to + // the first error message + QRegExp rx(QLatin1String("^l\\.(\\d+)(.*)")); + logLine = logStream->readLine(); + while (rx.indexIn(logLine) < 0 && !logStream->atEnd()) { + if (logLine.isEmpty()) + logText += QLatin1String("\n[LaTeX] Line ") + lineNum + QLatin1String(": "); + if (!logLine.startsWith( + QLatin1String("Type"))) // don't add lines that invite the user to type + // a command, since we are not in the console + logText += logLine; + logLine = logStream->readLine(); + } + logText += QLatin1Char('\n'); + if (logStream->atEnd()) + break; + + // add the line starting with "l. ..." and the next line + lineNum = QString::number(rx.cap(1).toInt() - 7); + logLine = QLatin1String("l.") + lineNum + rx.cap(2); + logText += logLine + QLatin1Char('\n'); + logText += logStream->readLine() + QLatin1Char('\n'); + } else { + for (int i = 1; i < errorMessageList.size(); ++i) { + if (logLine.contains(errorMessageList.at(i))) { + logText += logLine + QLatin1Char('\n'); + logText += logStream->readLine() + QLatin1Char('\n'); + logText += logStream->readLine() + + QLatin1Char( + '\n'); // we assume that the error message is not displayed + // on more than 3 lines in the log, so we stop here + break; + } + } + } + } + + return logText; } void TikzPreviewGenerator::parseLogFile() { - const QMutexLocker lock(&m_memberLock); - QString longLogText; - const QString latexLogFilePath = QFileInfo(m_tikzFileBaseName + QLatin1String(".log")).absoluteFilePath(); - QFile latexLogFile(latexLogFilePath); - if (!latexLogFile.open(QFile::ReadOnly | QIODevice::Text)) - { - if (!m_tikzCode.isEmpty()) - { - longLogText = QLatin1String("\n[LaTeX] ") + tr("Warning: could not load LaTeX log file.", "info process"); - m_shortLogText += longLogText; - longLogText += tr("\nLog file: %1", "info process").arg(latexLogFilePath); - Q_EMIT showErrorMessage(m_shortLogText); - Q_EMIT appendLog(longLogText, m_runFailed); - } - else - { -qCritical("does that ever happen?"); - m_shortLogText.clear(); - m_logText.clear(); - Q_EMIT updateLog(QString(), m_runFailed); - } - } - else - { - QTextStream latexLog(&latexLogFile); - if (m_runFailed && !m_shortLogText.contains(tr("Process aborted."))) - { - longLogText = getParsedLogText(&latexLog); - Q_EMIT updateLog(longLogText, m_runFailed); - } - latexLog.seek(0); - m_logText += latexLog.readAll(); - latexLogFile.close(); - } + const QMutexLocker lock(&m_memberLock); + QString longLogText; + const QString latexLogFilePath = + QFileInfo(m_tikzFileBaseName + QLatin1String(".log")).absoluteFilePath(); + QFile latexLogFile(latexLogFilePath); + if (!latexLogFile.open(QFile::ReadOnly | QIODevice::Text)) { + if (!m_tikzCode.isEmpty()) { + longLogText = QLatin1String("\n[LaTeX] ") + + tr("Warning: could not load LaTeX log file.", "info process"); + m_shortLogText += longLogText; + longLogText += tr("\nLog file: %1", "info process").arg(latexLogFilePath); + Q_EMIT showErrorMessage(m_shortLogText); + Q_EMIT appendLog(longLogText, m_runFailed); + } else { + qCritical("does that ever happen?"); + m_shortLogText.clear(); + m_logText.clear(); + Q_EMIT updateLog(QString(), m_runFailed); + } + } else { + QTextStream latexLog(&latexLogFile); + if (m_runFailed && !m_shortLogText.contains(tr("Process aborted."))) { + longLogText = getParsedLogText(&latexLog); + Q_EMIT updateLog(longLogText, m_runFailed); + } + latexLog.seek(0); + m_logText += latexLog.readAll(); + latexLogFile.close(); + } } /***************************************************************************/ static QList tikzCoordinates(const QString &tikzFileBaseName) { - QList tikzCoordinateList; - const QFileInfo tikzAuxFileInfo = QFileInfo(tikzFileBaseName + QLatin1String(".ktikzaux")); - QFile tikzAuxFile(tikzAuxFileInfo.absoluteFilePath()); - if (tikzAuxFile.open(QFile::ReadOnly | QIODevice::Text)) - { - QTextStream tikzAuxFileStream(&tikzAuxFile); - while (!tikzAuxFileStream.atEnd()) - { - QStringList tikzCoordinateStringList = tikzAuxFileStream.readLine().split(QLatin1Char(';')); - Q_FOREACH (const QString &tikzCoordinateString, tikzCoordinateStringList) - tikzCoordinateList << tikzCoordinateString.toDouble(); - } - } - return tikzCoordinateList; + QList tikzCoordinateList; + const QFileInfo tikzAuxFileInfo = QFileInfo(tikzFileBaseName + QLatin1String(".ktikzaux")); + QFile tikzAuxFile(tikzAuxFileInfo.absoluteFilePath()); + if (tikzAuxFile.open(QFile::ReadOnly | QIODevice::Text)) { + QTextStream tikzAuxFileStream(&tikzAuxFile); + while (!tikzAuxFileStream.atEnd()) { + QStringList tikzCoordinateStringList = + tikzAuxFileStream.readLine().split(QLatin1Char(';')); + Q_FOREACH (const QString &tikzCoordinateString, tikzCoordinateStringList) + tikzCoordinateList << tikzCoordinateString.toDouble(); + } + } + return tikzCoordinateList; } -static QString createTempLatexFile(const QString &tikzFileBaseName, const QString &templateFileName, const QString &tikzReplaceText, const TextCodecProfile *codecProfile); -static QString createTempTikzFile(const QString &tikzFileBaseName, const QString &tikzCode, const TextCodecProfile *codecProfile); +static QString createTempLatexFile(const QString &tikzFileBaseName, const QString &templateFileName, + const QString &tikzReplaceText, + const TextCodecProfile *codecProfile); +static QString createTempTikzFile(const QString &tikzFileBaseName, const QString &tikzCode, + const TextCodecProfile *codecProfile); void TikzPreviewGenerator::createPreview() { - // avoid that the user can export to a file while the preview is being generated - Q_EMIT setExportActionsEnabled(false); - - // avoid that the previous picture is still displayed - m_memberLock.lock(); - if (m_tikzCode.isEmpty()) - { - m_memberLock.unlock(); - return; - } - - // load template file if changed - if (m_templateChanged) - { - const QString errorString = createTempLatexFile(m_tikzFileBaseName, m_templateFileName, m_tikzReplaceText, m_parent->textCodecProfile()); - if (!errorString.isEmpty()) - { - showFileWriteError(m_tikzFileBaseName + QLatin1String(".tex"), errorString); - m_memberLock.unlock(); - return; - } - m_templateChanged = false; - } - - // load tikz code - const QString errorString = createTempTikzFile(m_tikzFileBaseName, m_tikzCode, m_parent->textCodecProfile()); - if (!errorString.isEmpty()) - { - showFileWriteError(m_tikzFileBaseName + QLatin1String(".pgf"), errorString); - m_memberLock.unlock(); - return; - } - - // compile everything, show preview and parse log - m_logText.clear(); - m_memberLock.unlock(); - if (generatePdfFile(m_tikzFileBaseName, m_latexCommand, m_useShellEscaping)) - { - m_memberLock.lock(); - const QFileInfo tikzPdfFileInfo(m_tikzFileBaseName + QLatin1String(".pdf")); - if (!tikzPdfFileInfo.exists()) - qWarning() << "Error:" << qPrintable(tikzPdfFileInfo.absoluteFilePath()) << "does not exist"; - else - { - // Update widget - if (m_tikzPdfDoc) - delete m_tikzPdfDoc; - m_tikzPdfDoc = Poppler::Document::load(tikzPdfFileInfo.absoluteFilePath()); - if (m_tikzPdfDoc) - { - m_shortLogText = QLatin1String("[LaTeX] ") + tr("Process finished successfully.", "info process"); - Q_EMIT pixmapUpdated(m_tikzPdfDoc, tikzCoordinates(m_tikzFileBaseName)); - Q_EMIT setExportActionsEnabled(true); - } - else - { - m_shortLogText = QLatin1String("[LaTeX] ") + tr("Error: loading PDF failed, the file is probably corrupted.", "info process"); - Q_EMIT showErrorMessage(m_shortLogText); - Q_EMIT updateLog(m_shortLogText + tr("\nPDF file: %1").arg(tikzPdfFileInfo.absoluteFilePath()), m_runFailed); - } - } - m_memberLock.unlock(); - } - parseLogFile(); + // avoid that the user can export to a file while the preview is being generated + Q_EMIT setExportActionsEnabled(false); + + // avoid that the previous picture is still displayed + m_memberLock.lock(); + if (m_tikzCode.isEmpty()) { + m_memberLock.unlock(); + return; + } + + // load template file if changed + if (m_templateChanged) { + const QString errorString = + createTempLatexFile(m_tikzFileBaseName, m_templateFileName, m_tikzReplaceText, + m_parent->textCodecProfile()); + if (!errorString.isEmpty()) { + showFileWriteError(m_tikzFileBaseName + QLatin1String(".tex"), errorString); + m_memberLock.unlock(); + return; + } + m_templateChanged = false; + } + + // load tikz code + const QString errorString = + createTempTikzFile(m_tikzFileBaseName, m_tikzCode, m_parent->textCodecProfile()); + if (!errorString.isEmpty()) { + showFileWriteError(m_tikzFileBaseName + QLatin1String(".pgf"), errorString); + m_memberLock.unlock(); + return; + } + + // compile everything, show preview and parse log + m_logText.clear(); + m_memberLock.unlock(); + if (generatePdfFile(m_tikzFileBaseName, m_latexCommand, m_useShellEscaping)) { + m_memberLock.lock(); + const QFileInfo tikzPdfFileInfo(m_tikzFileBaseName + QLatin1String(".pdf")); + if (!tikzPdfFileInfo.exists()) + qWarning() << "Error:" << qPrintable(tikzPdfFileInfo.absoluteFilePath()) + << "does not exist"; + else { + // Update widget + if (m_tikzPdfDoc) + delete m_tikzPdfDoc; + m_tikzPdfDoc = Poppler::Document::load(tikzPdfFileInfo.absoluteFilePath()); + if (m_tikzPdfDoc) { + m_shortLogText = QLatin1String("[LaTeX] ") + + tr("Process finished successfully.", "info process"); + Q_EMIT pixmapUpdated(m_tikzPdfDoc, tikzCoordinates(m_tikzFileBaseName)); + Q_EMIT setExportActionsEnabled(true); + } else { + m_shortLogText = QLatin1String("[LaTeX] ") + + tr("Error: loading PDF failed, the file is probably corrupted.", + "info process"); + Q_EMIT showErrorMessage(m_shortLogText); + Q_EMIT updateLog( + m_shortLogText + + tr("\nPDF file: %1").arg(tikzPdfFileInfo.absoluteFilePath()), + m_runFailed); + } + } + m_memberLock.unlock(); + } + parseLogFile(); } /***************************************************************************/ bool TikzPreviewGenerator::hasRunFailed() { - const QMutexLocker lock(&m_memberLock); - return m_runFailed; + const QMutexLocker lock(&m_memberLock); + return m_runFailed; } void TikzPreviewGenerator::generatePreview(TemplateStatus templateStatus) { - // Dirty hack because calling generatePreviewImpl directly from the main - // thread runs it in the main thread (only when triggered by a signal, - // it is run in the new thread). - // Note that abortProcess() must be run in the main thread; it kills - // previous calls to generatePreviewImpl() so that there is no - // interference between consecutive calls. - abortProcess(); - QMetaObject::invokeMethod(this, "generatePreviewImpl", Q_ARG(TemplateStatus, templateStatus)); + // Dirty hack because calling generatePreviewImpl directly from the main + // thread runs it in the main thread (only when triggered by a signal, + // it is run in the new thread). + // Note that abortProcess() must be run in the main thread; it kills + // previous calls to generatePreviewImpl() so that there is no + // interference between consecutive calls. + abortProcess(); + QMetaObject::invokeMethod(this, "generatePreviewImpl", Q_ARG(TemplateStatus, templateStatus)); } void TikzPreviewGenerator::generatePreviewImpl(TemplateStatus templateStatus) { - m_memberLock.lock(); - // Each time the tikz code is edited TikzPreviewController->regeneratePreview() - // is run, which runs generatePreview(DontReloadTemplate). This is OK - // in all cases, except at startup, because then the template is not yet - // copied to the temporary directory, so in order to make this happen, - // m_templateChanged should be set to true. - if (m_firstRun) - { - m_templateChanged = true; - m_firstRun = false; - } - else - m_templateChanged = (templateStatus == ReloadTemplate); - m_tikzCode = m_parent->tikzCode(); - m_runFailed = false; - m_memberLock.unlock(); - createPreview(); + m_memberLock.lock(); + // Each time the tikz code is edited TikzPreviewController->regeneratePreview() + // is run, which runs generatePreview(DontReloadTemplate). This is OK + // in all cases, except at startup, because then the template is not yet + // copied to the temporary directory, so in order to make this happen, + // m_templateChanged should be set to true. + if (m_firstRun) { + m_templateChanged = true; + m_firstRun = false; + } else + m_templateChanged = (templateStatus == ReloadTemplate); + m_tikzCode = m_parent->tikzCode(); + m_runFailed = false; + m_memberLock.unlock(); + createPreview(); } /***************************************************************************/ void TikzPreviewGenerator::showFileWriteError(const QString &fileName, const QString &errorMessage) { - const QString error = tr("Cannot write file \"%1\":\n%2").arg(fileName).arg(errorMessage); - Q_EMIT showErrorMessage(error); - Q_EMIT updateLog(error, true); + const QString error = tr("Cannot write file \"%1\":\n%2").arg(fileName).arg(errorMessage); + Q_EMIT showErrorMessage(error); + Q_EMIT updateLog(error, true); } -static QString createTempLatexFile(const QString &tikzFileBaseName, const QString &templateFileName, const QString &tikzReplaceText, const TextCodecProfile *codecProfile) +static QString createTempLatexFile(const QString &tikzFileBaseName, const QString &templateFileName, + const QString &tikzReplaceText, + const TextCodecProfile *codecProfile) { - const QString inputTikzCode = QLatin1String("\\makeatletter\n" - "\\ifdefined\\endtikzpicture%\n" - " \\newdimen\\ktikzorigx\n" - " \\newdimen\\ktikzorigy\n" - " \\newwrite\\ktikzauxfile\n" - " \\immediate\\openout\\ktikzauxfile\\jobname.ktikzaux\n" - " \\let\\oldendtikzpicture\\endtikzpicture\n" - " \\def\\endtikzpicture{%\n" - " \\pgfextractx{\\ktikzorigx}{\\pgfpointxy{1}{0}}\n" - " \\pgfextracty{\\ktikzorigy}{\\pgfpointxy{0}{1}}\n" - " \\pgfmathsetmacro{\\ktikzunitx}{\\ktikzorigx}\n" - " \\pgfmathsetmacro{\\ktikzunity}{\\ktikzorigy}\n" - " \\pgfmathsetmacro{\\ktikzminx}{\\csname pgf@picminx\\endcsname}\n" - " \\pgfmathsetmacro{\\ktikzmaxx}{\\csname pgf@picmaxx\\endcsname}\n" - " \\pgfmathsetmacro{\\ktikzminy}{\\csname pgf@picminy\\endcsname}\n" - " \\pgfmathsetmacro{\\ktikzmaxy}{\\csname pgf@picmaxy\\endcsname}\n" - " \\immediate\\write\\ktikzauxfile{\\ktikzunitx;\\ktikzunity;\\ktikzminx;\\ktikzmaxx;\\ktikzminy;\\ktikzmaxy}\n" - " \\oldendtikzpicture\n" - " }\n" - "\\fi\n" - "\\makeatother" + const QString inputTikzCode = + QLatin1String("\\makeatletter\n" + "\\ifdefined\\endtikzpicture%\n" + " \\newdimen\\ktikzorigx\n" + " \\newdimen\\ktikzorigy\n" + " \\newwrite\\ktikzauxfile\n" + " \\immediate\\openout\\ktikzauxfile\\jobname.ktikzaux\n" + " \\let\\oldendtikzpicture\\endtikzpicture\n" + " \\def\\endtikzpicture{%\n" + " \\pgfextractx{\\ktikzorigx}{\\pgfpointxy{1}{0}}\n" + " \\pgfextracty{\\ktikzorigy}{\\pgfpointxy{0}{1}}\n" + " \\pgfmathsetmacro{\\ktikzunitx}{\\ktikzorigx}\n" + " \\pgfmathsetmacro{\\ktikzunity}{\\ktikzorigy}\n" + " \\pgfmathsetmacro{\\ktikzminx}{\\csname pgf@picminx\\endcsname}\n" + " \\pgfmathsetmacro{\\ktikzmaxx}{\\csname pgf@picmaxx\\endcsname}\n" + " \\pgfmathsetmacro{\\ktikzminy}{\\csname pgf@picminy\\endcsname}\n" + " \\pgfmathsetmacro{\\ktikzmaxy}{\\csname pgf@picmaxy\\endcsname}\n" + " " + "\\immediate\\write\\ktikzauxfile{\\ktikzunitx;\\ktikzunity;\\ktikzminx;" + "\\ktikzmaxx;\\ktikzminy;\\ktikzmaxy}\n" + " \\oldendtikzpicture\n" + " }\n" + "\\fi\n" + "\\makeatother" #ifdef Q_OS_WIN32 - "\\input{") + QFileInfo(tikzFileBaseName).baseName() + QLatin1String(".pgf}" + "\\input{") + + QFileInfo(tikzFileBaseName).baseName() + + QLatin1String(".pgf}" #else - "\\input{") + tikzFileBaseName + QLatin1String(".pgf}" + "\\input{") + + tikzFileBaseName + + QLatin1String(".pgf}" #endif - "\\makeatletter\n" - "\\ifdefined\\endtikzpicture%\n" - " \\immediate\\closeout\\ktikzauxfile\n" - "\\fi\n" - "\\makeatother"); + "\\makeatletter\n" + "\\ifdefined\\endtikzpicture%\n" + " \\immediate\\closeout\\ktikzauxfile\n" + "\\fi\n" + "\\makeatother"); - File tikzTexFile(tikzFileBaseName + QLatin1String(".tex"), File::WriteOnly); - if (!tikzTexFile.open()) - return tikzTexFile.errorString(); + File tikzTexFile(tikzFileBaseName + QLatin1String(".tex"), File::WriteOnly); + if (!tikzTexFile.open()) + return tikzTexFile.errorString(); - QTextStream tikzStream(tikzTexFile.file()); - codecProfile->configureStreamEncoding(tikzStream); + QTextStream tikzStream(tikzTexFile.file()); + codecProfile->configureStreamEncoding(tikzStream); - QFile templateFile(templateFileName); + QFile templateFile(templateFileName); #ifdef KTIKZ_USE_KDE - KFileItem templateFileItem(QUrl::fromLocalFile(templateFileName)); - if (templateFileItem.determineMimeType().parentMimeTypes().contains(QLatin1String("text/plain")) + KFileItem templateFileItem(QUrl::fromLocalFile(templateFileName)); + if (templateFileItem.determineMimeType().parentMimeTypes().contains(QLatin1String("text/plain")) #else - if (QFileInfo(templateFile).isFile() + if (QFileInfo(templateFile).isFile() #endif - && templateFile.open(QIODevice::ReadOnly | QIODevice::Text) // if user-specified template file is readable - && !tikzReplaceText.isEmpty()) - { - QTextStream templateFileStream(&templateFile); - codecProfile->configureStreamDecoding(templateFileStream); - while (!templateFileStream.atEnd()) - { - QString templateLine = templateFileStream.readLine(); - if (templateLine.indexOf(tikzReplaceText) >= 0) - templateLine.replace(tikzReplaceText, inputTikzCode); - tikzStream << templateLine << QLatin1Char('\n'); - } - } - else // use our own template - { - tikzStream << QLatin1String("\\documentclass[12pt]{article}\n" - "\\usepackage{tikz}\n" - "\\usepackage{pgf}\n" - "\\usepackage[active,tightpage]{preview}\n" - "\\PreviewEnvironment[]{tikzpicture}\n" - "\\PreviewEnvironment[]{pgfpicture}\n" - "\\begin{document}\n") - << inputTikzCode << QLatin1Char('\n') - << QLatin1String("\\end{document}\n"); - } - - tikzStream.flush(); - - if (!tikzTexFile.close()) - return tikzTexFile.errorString(); - - qDebug() << "latex code written to:" << tikzFileBaseName + QLatin1String(".tex"); - return QString(); + && templateFile.open(QIODevice::ReadOnly + | QIODevice::Text) // if user-specified template file is readable + && !tikzReplaceText.isEmpty()) { + QTextStream templateFileStream(&templateFile); + codecProfile->configureStreamDecoding(templateFileStream); + while (!templateFileStream.atEnd()) { + QString templateLine = templateFileStream.readLine(); + if (templateLine.indexOf(tikzReplaceText) >= 0) + templateLine.replace(tikzReplaceText, inputTikzCode); + tikzStream << templateLine << QLatin1Char('\n'); + } + } else // use our own template + { + tikzStream << QLatin1String("\\documentclass[12pt]{article}\n" + "\\usepackage{tikz}\n" + "\\usepackage{pgf}\n" + "\\usepackage[active,tightpage]{preview}\n" + "\\PreviewEnvironment[]{tikzpicture}\n" + "\\PreviewEnvironment[]{pgfpicture}\n" + "\\begin{document}\n") + << inputTikzCode << QLatin1Char('\n') << QLatin1String("\\end{document}\n"); + } + + tikzStream.flush(); + + if (!tikzTexFile.close()) + return tikzTexFile.errorString(); + + qDebug() << "latex code written to:" << tikzFileBaseName + QLatin1String(".tex"); + return QString(); } -static QString createTempTikzFile(const QString &tikzFileBaseName, const QString &tikzCode, const TextCodecProfile *codecProfile) +static QString createTempTikzFile(const QString &tikzFileBaseName, const QString &tikzCode, + const TextCodecProfile *codecProfile) { - QFile tikzFile(tikzFileBaseName + QLatin1String(".pgf")); + QFile tikzFile(tikzFileBaseName + QLatin1String(".pgf")); - if (!tikzFile.open(QFile::WriteOnly)) - return QString::fromUtf8("Could not open \"%1\".").arg(tikzFileBaseName); + if (!tikzFile.open(QFile::WriteOnly)) + return QString::fromUtf8("Could not open \"%1\".").arg(tikzFileBaseName); - QTextStream tikzStream(&tikzFile); - codecProfile->configureStreamEncoding(tikzStream); + QTextStream tikzStream(&tikzFile); + codecProfile->configureStreamEncoding(tikzStream); - tikzStream << tikzCode << endl; - tikzStream.flush(); + tikzStream << tikzCode << endl; + tikzStream.flush(); - tikzFile.close(); + tikzFile.close(); - qDebug() << "tikz code written to:" << tikzFileBaseName + QLatin1String(".pgf"); - return QString(); + qDebug() << "tikz code written to:" << tikzFileBaseName + QLatin1String(".pgf"); + return QString(); } /***************************************************************************/ void TikzPreviewGenerator::addToLatexSearchPath(const QString &path) { - const QMutexLocker lock(&m_memberLock); - const QString texinputsValue = m_processEnvironment.value(QLatin1String("TEXINPUTS")); - const QString pathWithSeparator = path + s_pathSeparator; - if (!texinputsValue.contains(pathWithSeparator)) - m_processEnvironment.insert(QLatin1String("TEXINPUTS"), pathWithSeparator + texinputsValue); + const QMutexLocker lock(&m_memberLock); + const QString texinputsValue = m_processEnvironment.value(QLatin1String("TEXINPUTS")); + const QString pathWithSeparator = path + s_pathSeparator; + if (!texinputsValue.contains(pathWithSeparator)) + m_processEnvironment.insert(QLatin1String("TEXINPUTS"), pathWithSeparator + texinputsValue); } void TikzPreviewGenerator::removeFromLatexSearchPath(const QString &path) { - const QMutexLocker lock(&m_memberLock); - QString texinputsValue = m_processEnvironment.value(QLatin1String("TEXINPUTS")); - const QString pathWithSeparator = path + s_pathSeparator; - if (texinputsValue.contains(pathWithSeparator)) - m_processEnvironment.insert(QLatin1String("TEXINPUTS"), texinputsValue.remove(pathWithSeparator)); + const QMutexLocker lock(&m_memberLock); + QString texinputsValue = m_processEnvironment.value(QLatin1String("TEXINPUTS")); + const QString pathWithSeparator = path + s_pathSeparator; + if (texinputsValue.contains(pathWithSeparator)) + m_processEnvironment.insert(QLatin1String("TEXINPUTS"), + texinputsValue.remove(pathWithSeparator)); } bool TikzPreviewGenerator::runProcess(const QString &name, const QString &command, - const QStringList &arguments, const QString &workingDir) + const QStringList &arguments, const QString &workingDir) { - QString shortLogText; - QString longLogText; - bool runFailed = false; - - // Initialize process - m_memberLock.lock(); - m_process = new QProcess; - m_processAborted = false; - if (!workingDir.isEmpty()) - m_process->setWorkingDirectory(workingDir); - m_process->setProcessEnvironment(m_processEnvironment); - - // Start process - m_process->start(command, arguments); - m_memberLock.unlock(); // the following must not be protected by the mutex because we must be able to kill m_process - Q_EMIT processRunning(true); - if (!m_process->waitForStarted(1000)) - runFailed = true; - qDebug() << "starting" << command + QLatin1Char(' ') + arguments.join(QLatin1String(" ")); - - // Process is running - QByteArray buffer; - QTextStream log(&buffer); - while (m_process->state() != QProcess::NotRunning) - { - // still running or starting - if (m_process->bytesAvailable()) - log << m_process->readLine(); - else - m_process->waitForFinished(100 /*msec*/); - } - // Process finished - Q_EMIT processRunning(false); - if (m_process->bytesAvailable()) - log << m_process->readLine(m_process->bytesAvailable()); - log.seek(0); - - // Postprocessing - m_memberLock.lock(); - if (m_processAborted) - { - shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + tr("Process aborted.", "info process"); - longLogText = shortLogText; - runFailed = true; - } - else if (runFailed) // if the process could not be started - { - shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + tr("Error: the process could not be started.", "info process"); - longLogText = shortLogText + tr("\nCommand: %1", "info process").arg(command + QLatin1Char(' ') + arguments.join(QLatin1String(" "))); - } - else if (m_process->exitCode() == 0) - { - shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + tr("Process finished successfully.", "info process"); - longLogText = shortLogText; - runFailed = false; - } - else - { - shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + tr("Error: run failed.", "info process"); - longLogText = shortLogText + tr("\nCommand: %1", "info process").arg(command + QLatin1Char(' ') + arguments.join(QLatin1String(" "))); - qWarning() << "Error:" << qPrintable(command) << "run failed with exit code:" << m_process->exitCode(); - m_logText = log.readAll(); - runFailed = true; - } - delete m_process; - m_process = 0; - m_shortLogText = shortLogText; - m_runFailed = runFailed; - m_memberLock.unlock(); - - if (runFailed) - Q_EMIT showErrorMessage(shortLogText); - Q_EMIT updateLog(longLogText, runFailed); - - return !runFailed; + QString shortLogText; + QString longLogText; + bool runFailed = false; + + // Initialize process + m_memberLock.lock(); + m_process = new QProcess; + m_processAborted = false; + if (!workingDir.isEmpty()) + m_process->setWorkingDirectory(workingDir); + m_process->setProcessEnvironment(m_processEnvironment); + + // Start process + m_process->start(command, arguments); + m_memberLock.unlock(); // the following must not be protected by the mutex because we must be + // able to kill m_process + Q_EMIT processRunning(true); + if (!m_process->waitForStarted(1000)) + runFailed = true; + qDebug() << "starting" << command + QLatin1Char(' ') + arguments.join(QLatin1String(" ")); + + // Process is running + QByteArray buffer; + QTextStream log(&buffer); + while (m_process->state() != QProcess::NotRunning) { + // still running or starting + if (m_process->bytesAvailable()) + log << m_process->readLine(); + else + m_process->waitForFinished(100 /*msec*/); + } + // Process finished + Q_EMIT processRunning(false); + if (m_process->bytesAvailable()) + log << m_process->readLine(m_process->bytesAvailable()); + log.seek(0); + + // Postprocessing + m_memberLock.lock(); + if (m_processAborted) { + shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + + tr("Process aborted.", "info process"); + longLogText = shortLogText; + runFailed = true; + } else if (runFailed) // if the process could not be started + { + shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + + tr("Error: the process could not be started.", "info process"); + longLogText = shortLogText + + tr("\nCommand: %1", "info process") + .arg(command + QLatin1Char(' ') + arguments.join(QLatin1String(" "))); + } else if (m_process->exitCode() == 0) { + shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + + tr("Process finished successfully.", "info process"); + longLogText = shortLogText; + runFailed = false; + } else { + shortLogText = QLatin1Char('[') + name + QLatin1String("] ") + + tr("Error: run failed.", "info process"); + longLogText = shortLogText + + tr("\nCommand: %1", "info process") + .arg(command + QLatin1Char(' ') + arguments.join(QLatin1String(" "))); + qWarning() << "Error:" << qPrintable(command) + << "run failed with exit code:" << m_process->exitCode(); + m_logText = log.readAll(); + runFailed = true; + } + delete m_process; + m_process = 0; + m_shortLogText = shortLogText; + m_runFailed = runFailed; + m_memberLock.unlock(); + + if (runFailed) + Q_EMIT showErrorMessage(shortLogText); + Q_EMIT updateLog(longLogText, runFailed); + + return !runFailed; } void TikzPreviewGenerator::abortProcess() { - if (m_process) - { - m_process->kill(); - m_processAborted = true; - } + if (m_process) { + m_process->kill(); + m_processAborted = true; + } } /***************************************************************************/ bool TikzPreviewGenerator::generateEpsFile(int page) { - QStringList pdftopsArguments; - pdftopsArguments << QLatin1String("-f") << QString::number(page+1) << QLatin1String("-l") << QString::number(page+1) << QLatin1String("-eps") << m_tikzFileBaseName + QLatin1String(".pdf") << m_tikzFileBaseName + QLatin1String(".eps"); - return runProcess(QLatin1String("pdftops"), m_pdftopsCommand, pdftopsArguments); -/* - int width = m_tikzPdfDoc->page(page)->pageSize().width(); - int height = m_tikzPdfDoc->page(page)->pageSize().height(); - - Poppler::PSConverter *psConverter = m_tikzPdfDoc->psConverter(); - psConverter->setOutputFileName(m_tikzFileBaseName + QLatin1String(".eps")); - psConverter->setPageList(QList() << page+1); - psConverter->setPaperWidth(width); - psConverter->setPaperHeight(height); - if (psConverter->convert()) - { - delete psConverter; - return true; - } - delete psConverter; - return false; -*/ + QStringList pdftopsArguments; + pdftopsArguments << QLatin1String("-f") << QString::number(page + 1) << QLatin1String("-l") + << QString::number(page + 1) << QLatin1String("-eps") + << m_tikzFileBaseName + QLatin1String(".pdf") + << m_tikzFileBaseName + QLatin1String(".eps"); + return runProcess(QLatin1String("pdftops"), m_pdftopsCommand, pdftopsArguments); + /* + int width = m_tikzPdfDoc->page(page)->pageSize().width(); + int height = m_tikzPdfDoc->page(page)->pageSize().height(); + + Poppler::PSConverter *psConverter = m_tikzPdfDoc->psConverter(); + psConverter->setOutputFileName(m_tikzFileBaseName + QLatin1String(".eps")); + psConverter->setPageList(QList() << page+1); + psConverter->setPaperWidth(width); + psConverter->setPaperHeight(height); + if (psConverter->convert()) + { + delete psConverter; + return true; + } + delete psConverter; + return false; + */ } -bool TikzPreviewGenerator::generatePdfFile(const QString &tikzFileBaseName, const QString &latexCommand, bool useShellEscaping) +bool TikzPreviewGenerator::generatePdfFile(const QString &tikzFileBaseName, + const QString &latexCommand, bool useShellEscaping) { - // remove log file before running pdflatex again - QDir::root().remove(tikzFileBaseName + QLatin1String(".log")); - - QStringList arguments; - if (latexCommand == QLatin1String("context")) { - // ConTeXt doesn’t support enabling \write18 via command line - arguments << QLatin1String("--nonstopmode"); - } else { - if (useShellEscaping) - arguments << QLatin1String("-shell-escape"); - arguments << QLatin1String("-halt-on-error") << QLatin1String("-file-line-error") - << QLatin1String("-interaction") << QLatin1String("nonstopmode"); - } - // We run the command in the temp dir, so using the file name is enough - arguments << QFileInfo(tikzFileBaseName + QLatin1String(".tex")).fileName(); - - Q_EMIT updateLog(QLatin1String("[LaTeX] ") + tr("Running...", "info process"), false); // runFailed = false - return runProcess(QLatin1String("LaTeX"), latexCommand, arguments, QFileInfo(tikzFileBaseName).absolutePath()); + // remove log file before running pdflatex again + QDir::root().remove(tikzFileBaseName + QLatin1String(".log")); + + QStringList arguments; + if (latexCommand == QLatin1String("context")) { + // ConTeXt doesn’t support enabling \write18 via command line + arguments << QLatin1String("--nonstopmode"); + } else { + if (useShellEscaping) + arguments << QLatin1String("-shell-escape"); + arguments << QLatin1String("-halt-on-error") << QLatin1String("-file-line-error") + << QLatin1String("-interaction") << QLatin1String("nonstopmode"); + } + // We run the command in the temp dir, so using the file name is enough + arguments << QFileInfo(tikzFileBaseName + QLatin1String(".tex")).fileName(); + + Q_EMIT updateLog(QLatin1String("[LaTeX] ") + tr("Running...", "info process"), + false); // runFailed = false + return runProcess(QLatin1String("LaTeX"), latexCommand, arguments, + QFileInfo(tikzFileBaseName).absolutePath()); } diff --git a/common/tikzpreviewgenerator.h b/common/tikzpreviewgenerator.h index 92846f5..6d3de1e 100644 --- a/common/tikzpreviewgenerator.h +++ b/common/tikzpreviewgenerator.h @@ -33,8 +33,7 @@ class QProcess; class QPlainEdit; class QTextStream; -namespace Poppler -{ +namespace Poppler { class Document; } @@ -46,75 +45,74 @@ class TikzPreviewController; */ class TikzPreviewGenerator : public QObject { - Q_OBJECT + Q_OBJECT public: - enum TemplateStatus - { - DontReloadTemplate = 0, - ReloadTemplate = 1 - }; - - explicit TikzPreviewGenerator(TikzPreviewController *parent); - ~TikzPreviewGenerator(); - - void setTikzFileBaseName(const QString &name); - void setLatexCommand(const QString &command); - void setPdftopsCommand(const QString &command); - void setShellEscaping(bool useShellEscaping); - QString getLogText() const; - bool hasRunFailed(); - void addToLatexSearchPath(const QString &path); - void removeFromLatexSearchPath(const QString &path); - bool generateEpsFile(int page); + enum TemplateStatus { DontReloadTemplate = 0, ReloadTemplate = 1 }; + + explicit TikzPreviewGenerator(TikzPreviewController *parent); + ~TikzPreviewGenerator(); + + void setTikzFileBaseName(const QString &name); + void setLatexCommand(const QString &command); + void setPdftopsCommand(const QString &command); + void setShellEscaping(bool useShellEscaping); + QString getLogText() const; + bool hasRunFailed(); + void addToLatexSearchPath(const QString &path); + void removeFromLatexSearchPath(const QString &path); + bool generateEpsFile(int page); public Q_SLOTS: - void setTemplateFile(const QString &fileName); - void setReplaceText(const QString &replace); - void generatePreview(TemplateStatus templateStatus = DontReloadTemplate); - void abortProcess(); + void setTemplateFile(const QString &fileName); + void setReplaceText(const QString &replace); + void generatePreview(TemplateStatus templateStatus = DontReloadTemplate); + void abortProcess(); Q_SIGNALS: - void pixmapUpdated(Poppler::Document *tikzPdfDoc, const QList &tikzCoordinates = QList()); - void setExportActionsEnabled(bool enabled); - void showErrorMessage(const QString &message); - void updateLog(const QString &logText, bool runFailed); - void appendLog(const QString &logText, bool runFailed); - void processRunning(bool isRunning); + void pixmapUpdated(Poppler::Document *tikzPdfDoc, + const QList &tikzCoordinates = QList()); + void setExportActionsEnabled(bool enabled); + void showErrorMessage(const QString &message); + void updateLog(const QString &logText, bool runFailed); + void appendLog(const QString &logText, bool runFailed); + void processRunning(bool isRunning); private Q_SLOTS: - void generatePreviewImpl(TemplateStatus templateStatus = DontReloadTemplate); + void generatePreviewImpl(TemplateStatus templateStatus = DontReloadTemplate); protected: - void parseLogFile(); - void createPreview(); - void showFileWriteError(const QString &fileName, const QString &errorMessage); - bool runProcess(const QString &name, const QString &command, const QStringList &arguments, const QString &workingDir = QString()); - bool generatePdfFile(const QString &tikzFileBaseName, const QString &latexCommand, bool useShellEscaping); - - TikzPreviewController *m_parent; - Poppler::Document *m_tikzPdfDoc; - QString m_tikzCode; - - QThread m_thread; - - QProcess *m_process; - mutable QMutex m_memberLock; - bool m_processAborted; - bool m_runFailed; - QProcessEnvironment m_processEnvironment; - bool m_firstRun; - - QString m_tikzFileBaseName; - QString m_templateFileName; - QString m_tikzReplaceText; - bool m_templateChanged; - - QString m_latexCommand; - QString m_pdftopsCommand; - QString m_shortLogText; - QString m_logText; - bool m_useShellEscaping; + void parseLogFile(); + void createPreview(); + void showFileWriteError(const QString &fileName, const QString &errorMessage); + bool runProcess(const QString &name, const QString &command, const QStringList &arguments, + const QString &workingDir = QString()); + bool generatePdfFile(const QString &tikzFileBaseName, const QString &latexCommand, + bool useShellEscaping); + + TikzPreviewController *m_parent; + Poppler::Document *m_tikzPdfDoc; + QString m_tikzCode; + + QThread m_thread; + + QProcess *m_process; + mutable QMutex m_memberLock; + bool m_processAborted; + bool m_runFailed; + QProcessEnvironment m_processEnvironment; + bool m_firstRun; + + QString m_tikzFileBaseName; + QString m_templateFileName; + QString m_tikzReplaceText; + bool m_templateChanged; + + QString m_latexCommand; + QString m_pdftopsCommand; + QString m_shortLogText; + QString m_logText; + bool m_useShellEscaping; }; #endif diff --git a/common/tikzpreviewmessagewidget.cpp b/common/tikzpreviewmessagewidget.cpp index 805601e..432d818 100644 --- a/common/tikzpreviewmessagewidget.cpp +++ b/common/tikzpreviewmessagewidget.cpp @@ -21,74 +21,67 @@ #include #include #ifdef KTIKZ_USE_KDE -#include +# include #endif #include "utils/icon.h" -TikzPreviewMessageWidget::TikzPreviewMessageWidget(QWidget *parent) - : QFrame(parent) +TikzPreviewMessageWidget::TikzPreviewMessageWidget(QWidget *parent) : QFrame(parent) { #ifdef KTIKZ_USE_KDE - const QPixmap infoPixmap = KIconLoader::global()->loadIcon(QLatin1String("dialog-error"), - KIconLoader::Dialog, KIconLoader::SizeMedium); + const QPixmap infoPixmap = KIconLoader::global()->loadIcon( + QLatin1String("dialog-error"), KIconLoader::Dialog, KIconLoader::SizeMedium); #else - const QPixmap infoPixmap = Icon(QLatin1String("dialog-error")).pixmap(QSize(32, 32)); + const QPixmap infoPixmap = Icon(QLatin1String("dialog-error")).pixmap(QSize(32, 32)); #endif - m_infoPixmapLabel = new QLabel; - m_infoPixmapLabel->setPixmap(infoPixmap); + m_infoPixmapLabel = new QLabel; + m_infoPixmapLabel->setPixmap(infoPixmap); - m_infoLabel = new QLabel; - m_infoLabel->setWordWrap(true); - m_infoLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + m_infoLabel = new QLabel; + m_infoLabel->setWordWrap(true); + m_infoLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - setObjectName(QLatin1String("PreviewMessageWidget")); - setFrameShape(QFrame::Box); + setObjectName(QLatin1String("PreviewMessageWidget")); + setFrameShape(QFrame::Box); - setStyleSheet(QString(QLatin1String( - "QFrame {" - " background-color: palette(midlight);" - " border-radius: 5px;" - " border: 1px solid palette(dark);" - "}" - "QLabel {" - " border: none;" - " color: palette(windowText);" - "}" - ))); + setStyleSheet(QString(QLatin1String("QFrame {" + " background-color: palette(midlight);" + " border-radius: 5px;" + " border: 1px solid palette(dark);" + "}" + "QLabel {" + " border: none;" + " color: palette(windowText);" + "}"))); - QHBoxLayout *infoLayout = new QHBoxLayout(this); - infoLayout->setMargin(10); - infoLayout->addWidget(m_infoPixmapLabel); - infoLayout->addWidget(m_infoLabel); + QHBoxLayout *infoLayout = new QHBoxLayout(this); + infoLayout->setMargin(10); + infoLayout->addWidget(m_infoPixmapLabel); + infoLayout->addWidget(m_infoLabel); - m_infoPixmapLabel->setVisible(false); + m_infoPixmapLabel->setVisible(false); } -TikzPreviewMessageWidget::~TikzPreviewMessageWidget() -{ -} +TikzPreviewMessageWidget::~TikzPreviewMessageWidget() { } QSize TikzPreviewMessageWidget::calculateSize(bool pixmapVisible) const { - if (pixmapVisible) - { - return QSize(m_infoPixmapLabel->sizeHint().width() - + m_infoLabel->sizeHint().width() + 35, - qMax(m_infoPixmapLabel->sizeHint().height(), m_infoLabel->sizeHint().height()) + 25); - } - return QSize(m_infoLabel->sizeHint().width() + 25, - m_infoLabel->sizeHint().height() + 25); + if (pixmapVisible) { + return QSize(m_infoPixmapLabel->sizeHint().width() + m_infoLabel->sizeHint().width() + 35, + qMax(m_infoPixmapLabel->sizeHint().height(), m_infoLabel->sizeHint().height()) + + 25); + } + return QSize(m_infoLabel->sizeHint().width() + 25, m_infoLabel->sizeHint().height() + 25); } QSize TikzPreviewMessageWidget::sizeHint() const { - return calculateSize(m_infoPixmapLabel->isVisible()); + return calculateSize(m_infoPixmapLabel->isVisible()); } void TikzPreviewMessageWidget::setText(const QString &message, PixmapVisibility pixmapVisibility) { - m_infoPixmapLabel->setVisible(pixmapVisibility == PixmapVisible); - m_infoLabel->setText(message); - resize(calculateSize(pixmapVisibility == PixmapVisible)); + m_infoPixmapLabel->setVisible(pixmapVisibility == PixmapVisible); + m_infoLabel->setText(message); + resize(calculateSize(pixmapVisibility == PixmapVisible)); } diff --git a/common/tikzpreviewmessagewidget.h b/common/tikzpreviewmessagewidget.h index 3c912ba..fe07cc3 100644 --- a/common/tikzpreviewmessagewidget.h +++ b/common/tikzpreviewmessagewidget.h @@ -26,26 +26,22 @@ class QLabel; class TikzPreviewMessageWidget : public QFrame { - Q_OBJECT + Q_OBJECT public: - enum PixmapVisibility - { - PixmapNotVisible = 0, - PixmapVisible = 1 - }; + enum PixmapVisibility { PixmapNotVisible = 0, PixmapVisible = 1 }; - explicit TikzPreviewMessageWidget(QWidget *parent = 0); - ~TikzPreviewMessageWidget(); + explicit TikzPreviewMessageWidget(QWidget *parent = 0); + ~TikzPreviewMessageWidget(); - virtual QSize sizeHint() const; - void setText(const QString &message, PixmapVisibility pixmapVisibility = PixmapNotVisible); + virtual QSize sizeHint() const; + void setText(const QString &message, PixmapVisibility pixmapVisibility = PixmapNotVisible); private: - QSize calculateSize(bool pixmapVisible) const; + QSize calculateSize(bool pixmapVisible) const; - QLabel *m_infoPixmapLabel; - QLabel *m_infoLabel; + QLabel *m_infoPixmapLabel; + QLabel *m_infoLabel; }; #endif diff --git a/common/tikzpreviewrenderer.cpp b/common/tikzpreviewrenderer.cpp index fd997d2..372bea4 100644 --- a/common/tikzpreviewrenderer.cpp +++ b/common/tikzpreviewrenderer.cpp @@ -23,24 +23,24 @@ TikzPreviewRenderer::TikzPreviewRenderer() { - moveToThread(&m_thread); - m_thread.start(); + moveToThread(&m_thread); + m_thread.start(); } TikzPreviewRenderer::~TikzPreviewRenderer() { - if (m_thread.isRunning()) - { - m_thread.quit(); - m_thread.wait(); - } + if (m_thread.isRunning()) { + m_thread.quit(); + m_thread.wait(); + } } -void TikzPreviewRenderer::generatePreview(Poppler::Document *tikzPdfDoc, qreal zoomFactor, int currentPage) +void TikzPreviewRenderer::generatePreview(Poppler::Document *tikzPdfDoc, qreal zoomFactor, + int currentPage) { - Poppler::Page *pdfPage = tikzPdfDoc->page(currentPage); - const QImage tikzImage = pdfPage->renderToImage(zoomFactor * 72, zoomFactor * 72); - delete pdfPage; + Poppler::Page *pdfPage = tikzPdfDoc->page(currentPage); + const QImage tikzImage = pdfPage->renderToImage(zoomFactor * 72, zoomFactor * 72); + delete pdfPage; - Q_EMIT showPreview(tikzImage, zoomFactor); + Q_EMIT showPreview(tikzImage, zoomFactor); } diff --git a/common/tikzpreviewrenderer.h b/common/tikzpreviewrenderer.h index 62a19b7..f5ac69d 100644 --- a/common/tikzpreviewrenderer.h +++ b/common/tikzpreviewrenderer.h @@ -23,27 +23,27 @@ class QImage; -namespace Poppler -{ +namespace Poppler { class Document; } class TikzPreviewRenderer : public QObject { - Q_OBJECT + Q_OBJECT public: - TikzPreviewRenderer(); - ~TikzPreviewRenderer(); + TikzPreviewRenderer(); + ~TikzPreviewRenderer(); public Q_SLOTS: - void generatePreview(Poppler::Document *tikzPdfDoc, qreal zoomFactor = 1.0, int currentPage = 0); + void generatePreview(Poppler::Document *tikzPdfDoc, qreal zoomFactor = 1.0, + int currentPage = 0); Q_SIGNALS: - void showPreview(const QImage &image, qreal zoomFactor = 1.0); + void showPreview(const QImage &image, qreal zoomFactor = 1.0); private: - QThread m_thread; + QThread m_thread; }; #endif diff --git a/common/utils/action.cpp b/common/utils/action.cpp index 2a768c0..7ab2068 100644 --- a/common/utils/action.cpp +++ b/common/utils/action.cpp @@ -20,69 +20,65 @@ #include "icon.h" #ifdef KTIKZ_USE_KDE -#include +# include KActionCollection *Action::s_actionCollection = 0; -Action::Action(QObject *parent, const QString &name) - : QAction(parent) +Action::Action(QObject *parent, const QString &name) : QAction(parent) { - if (s_actionCollection && !name.isEmpty()) - s_actionCollection->addAction(name, this); + if (s_actionCollection && !name.isEmpty()) + s_actionCollection->addAction(name, this); } -Action::Action(const QString &text, QObject *parent, const QString &name) - : QAction(text, parent) +Action::Action(const QString &text, QObject *parent, const QString &name) : QAction(text, parent) { - if (s_actionCollection && !name.isEmpty()) - s_actionCollection->addAction(name, this); + if (s_actionCollection && !name.isEmpty()) + s_actionCollection->addAction(name, this); } Action::Action(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : QAction(icon, text, parent) + : QAction(icon, text, parent) { - if (s_actionCollection && !name.isEmpty()) - s_actionCollection->addAction(name, this); + if (s_actionCollection && !name.isEmpty()) + s_actionCollection->addAction(name, this); } void Action::setShortcut(const QKeySequence &shortcut) { - actionCollection()->setDefaultShortcut( this, shortcut ); + actionCollection()->setDefaultShortcut(this, shortcut); } KActionCollection *Action::actionCollection() { - return s_actionCollection; + return s_actionCollection; } void Action::setActionCollection(KActionCollection *actionCollection) { - s_actionCollection = actionCollection; + s_actionCollection = actionCollection; } #else -Action::Action(QObject *parent, const QString &name) - : QAction(parent) +Action::Action(QObject *parent, const QString &name) : QAction(parent) { - if (!name.isEmpty()) - setObjectName(name); + if (!name.isEmpty()) + setObjectName(name); } -Action::Action(const QString &text, QObject *parent, const QString &name) - : QAction(text, parent) +Action::Action(const QString &text, QObject *parent, const QString &name) : QAction(text, parent) { - if (!name.isEmpty()) - setObjectName(name); + if (!name.isEmpty()) + setObjectName(name); } Action::Action(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : QAction(icon, text, parent) + : QAction(icon, text, parent) { - if (!name.isEmpty()) - setObjectName(name); + if (!name.isEmpty()) + setObjectName(name); } void Action::setShortcut(const QKeySequence &shortcut) { - QAction::setShortcut(shortcut); + QAction::setShortcut(shortcut); } #endif diff --git a/common/utils/action.h b/common/utils/action.h index 53efe51..030cec1 100644 --- a/common/utils/action.h +++ b/common/utils/action.h @@ -25,23 +25,23 @@ class KActionCollection; class Icon; -class Action: public QAction +class Action : public QAction { - Q_OBJECT + Q_OBJECT public: - explicit Action(QObject *parent, const QString &name = QString()); - Action(const QString &text, QObject *parent, const QString &name = QString()); - Action(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); + explicit Action(QObject *parent, const QString &name = QString()); + Action(const QString &text, QObject *parent, const QString &name = QString()); + Action(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); - void setShortcut(const QKeySequence &shortcut); + void setShortcut(const QKeySequence &shortcut); #ifdef KTIKZ_USE_KDE - static KActionCollection *actionCollection(); - static void setActionCollection(KActionCollection *actionCollection); + static KActionCollection *actionCollection(); + static void setActionCollection(KActionCollection *actionCollection); private: - static KActionCollection *s_actionCollection; + static KActionCollection *s_actionCollection; #endif }; diff --git a/common/utils/colorbutton.cpp b/common/utils/colorbutton.cpp index b5df5fa..cd7f737 100644 --- a/common/utils/colorbutton.cpp +++ b/common/utils/colorbutton.cpp @@ -24,53 +24,53 @@ #include "colorbutton.h" #ifndef KTIKZ_USE_KDE -#include -#include -#include +# include +# include +# include ColorButton::ColorButton(QWidget *parent) : QToolButton(parent) { - connect(this, SIGNAL(clicked()), this, SLOT(showColorDialog())); + connect(this, SIGNAL(clicked()), this, SLOT(showColorDialog())); } ColorButton::ColorButton(const QColor &color, QWidget *parent) : QToolButton(parent) { - setColor(color); - connect(this, SIGNAL(clicked()), this, SLOT(showColorDialog())); + setColor(color); + connect(this, SIGNAL(clicked()), this, SLOT(showColorDialog())); } void ColorButton::showColorDialog() { - const QColor newColor = QColorDialog::getColor(m_color, this); - if (newColor.isValid()) - setColor(newColor); + const QColor newColor = QColorDialog::getColor(m_color, this); + if (newColor.isValid()) + setColor(newColor); } QColor ColorButton::color() const { - return m_color; + return m_color; } void ColorButton::setColor(const QColor &color) { - m_color = color; - Q_EMIT colorChanged(color); - update(); + m_color = color; + Q_EMIT colorChanged(color); + update(); } void ColorButton::paintEvent(QPaintEvent *event) { - QToolButton::paintEvent(event); - if (!isEnabled()) - return; + QToolButton::paintEvent(event); + if (!isEnabled()) + return; - QRect r = rect(); - r.adjust(5, 5, -5, -5); - QPainter painter(this); - const QColor borderColor(QApplication::palette().color(QPalette::Normal, QPalette::Dark)); - painter.setPen(borderColor); - painter.drawRect(r); - r.adjust(1, 1, 0, 0); - painter.fillRect(r, m_color); + QRect r = rect(); + r.adjust(5, 5, -5, -5); + QPainter painter(this); + const QColor borderColor(QApplication::palette().color(QPalette::Normal, QPalette::Dark)); + painter.setPen(borderColor); + painter.drawRect(r); + r.adjust(1, 1, 0, 0); + painter.fillRect(r, m_color); } #endif diff --git a/common/utils/colorbutton.h b/common/utils/colorbutton.h index 45cc75e..0d0f7f1 100644 --- a/common/utils/colorbutton.h +++ b/common/utils/colorbutton.h @@ -20,43 +20,43 @@ #define KTIKZ_COLORBUTTON_H #ifdef KTIKZ_USE_KDE -#include +# include class ColorButton : public KColorButton { - Q_OBJECT + Q_OBJECT public: - explicit ColorButton(QWidget *parent = 0) : KColorButton(parent) {} - explicit ColorButton(const QColor &color, QWidget *parent = 0) : KColorButton(color, parent) {} + explicit ColorButton(QWidget *parent = 0) : KColorButton(parent) { } + explicit ColorButton(const QColor &color, QWidget *parent = 0) : KColorButton(color, parent) { } }; #else -#include -#include +# include +# include class ColorButton : public QToolButton { - Q_OBJECT - Q_PROPERTY(QColor color READ color WRITE setColor) + Q_OBJECT + Q_PROPERTY(QColor color READ color WRITE setColor) public: - explicit ColorButton(QWidget *parent = 0); - explicit ColorButton(const QColor &color, QWidget *parent = 0); + explicit ColorButton(QWidget *parent = 0); + explicit ColorButton(const QColor &color, QWidget *parent = 0); - QColor color() const; - void setColor(const QColor &color); + QColor color() const; + void setColor(const QColor &color); Q_SIGNALS: - void colorChanged(const QColor &newColor); + void colorChanged(const QColor &newColor); protected: - void paintEvent(QPaintEvent*); + void paintEvent(QPaintEvent *); private Q_SLOTS: - void showColorDialog(); + void showColorDialog(); private: - QColor m_color; + QColor m_color; }; #endif diff --git a/common/utils/colordialog.h b/common/utils/colordialog.h index 3ec763c..1339e16 100644 --- a/common/utils/colordialog.h +++ b/common/utils/colordialog.h @@ -24,16 +24,16 @@ class ColorDialog : public QColorDialog { public: - // Commented out for Qt 4.5 compatibility (should not be required, - // as we don't instantiate ColorDialog directly anyway - //explicit ColorDialog(QWidget *parent) : QColorDialog(parent) {} + // Commented out for Qt 4.5 compatibility (should not be required, + // as we don't instantiate ColorDialog directly anyway + // explicit ColorDialog(QWidget *parent) : QColorDialog(parent) {} - static QColor getColor(bool *ok, const QColor &color, QWidget *parent) - { - const QColor newColor = QColorDialog::getColor(color, parent); - *ok = newColor.isValid(); - return newColor; - } + static QColor getColor(bool *ok, const QColor &color, QWidget *parent) + { + const QColor newColor = QColorDialog::getColor(color, parent); + *ok = newColor.isValid(); + return newColor; + } }; #endif diff --git a/common/utils/combobox.cpp b/common/utils/combobox.cpp index f758824..1570f5c 100644 --- a/common/utils/combobox.cpp +++ b/common/utils/combobox.cpp @@ -19,18 +19,14 @@ #include "combobox.h" #ifdef KTIKZ_USE_KDE -ComboBox::ComboBox(QWidget *parent) : KComboBox(parent) -{ -} +ComboBox::ComboBox(QWidget *parent) : KComboBox(parent) { } #else -#include "urlcompletion.h" +# include "urlcompletion.h" -ComboBox::ComboBox(QWidget *parent) : QComboBox(parent) -{ -} +ComboBox::ComboBox(QWidget *parent) : QComboBox(parent) { } void ComboBox::setCompletionObject(UrlCompletion *urlCompletion) { - setCompleter(urlCompletion); + setCompleter(urlCompletion); } #endif diff --git a/common/utils/combobox.h b/common/utils/combobox.h index 4a2a745..1512b09 100644 --- a/common/utils/combobox.h +++ b/common/utils/combobox.h @@ -20,26 +20,26 @@ #define KTIKZ_COMBOBOX_H #ifdef KTIKZ_USE_KDE -#include +# include class ComboBox : public KComboBox { - Q_OBJECT + Q_OBJECT public: - explicit ComboBox(QWidget *parent = 0); + explicit ComboBox(QWidget *parent = 0); }; #else -#include -#include +# include +# include class UrlCompletion; class ComboBox : public QComboBox { - Q_OBJECT + Q_OBJECT public: - explicit ComboBox(QWidget *parent = 0); - void setCompletionObject(UrlCompletion *urlCompletion); + explicit ComboBox(QWidget *parent = 0); + void setCompletionObject(UrlCompletion *urlCompletion); }; #endif diff --git a/common/utils/file.cpp b/common/utils/file.cpp index 58e7a52..e1d1ddc 100644 --- a/common/utils/file.cpp +++ b/common/utils/file.cpp @@ -20,37 +20,32 @@ #include "url.h" #ifdef KTIKZ_USE_KDE -#include -#include -//#include +# include +# include +// #include QWidget *File::s_mainWidget; QString File::s_tempDir; File::File(const QString &fileName, const OpenMode &mode) - : m_openMode(mode) - , m_url(QUrl::fromUserInput(fileName)) + : m_openMode(mode), m_url(QUrl::fromUserInput(fileName)) { - load(); + load(); } -File::File(const QUrl &url, const OpenMode &mode) - : m_openMode(mode) - , m_url(url) +File::File(const QUrl &url, const OpenMode &mode) : m_openMode(mode), m_url(url) { - load(); + load(); } - bool File::fileExists(const QUrl &url) { - if (!(url.isValid())) - { - return false; - } - KIO::StatJob * existsJob = KIO::stat(url, KIO::StatJob::DestinationSide, 0); - existsJob->exec(); - return (existsJob->error() == KJob::NoError); + if (!(url.isValid())) { + return false; + } + KIO::StatJob *existsJob = KIO::stat(url, KIO::StatJob::DestinationSide, 0); + existsJob->exec(); + return (existsJob->error() == KJob::NoError); } /*! @@ -62,88 +57,87 @@ bool File::fileExists(const QUrl &url) void File::load() { - m_errorString.clear(); - - if (!m_url.isValid()) - { - m_file = new QFile(); - return; - } - - // We assume for simplicity that s_tempDir is not empty, this is the - // case because a TikzPreviewController object is created at startup - // and in its constructor setTempDir() is called. - Q_ASSERT_X(!s_tempDir.isEmpty(), "loading a file", "File::setTempDir(const QString &dirName) must be called before constructing any File object"); - m_localFileName = m_url.isLocalFile() ? m_url.path() : s_tempDir + m_url.fileName(); - - if (m_openMode == WriteOnly) - { - //m_file = new KSaveFile(m_localFileName); - m_file = new QFile(m_localFileName); - } - else if (m_openMode == ReadOnly) - { - if (!m_url.isLocalFile() && File::fileExists(m_url) ) - { - KIO::Job *job = KIO::file_copy(m_url, QUrl::fromLocalFile(m_localFileName), -1, KIO::Overwrite | KIO::HideProgressInfo); - KJobWidgets::setWindow(job, s_mainWidget); - if (!job->exec()) - { - m_errorString = tr("Could not copy \"%1\" to temporary file \"%2\".").arg(m_url.toDisplayString()).arg(m_localFileName); - return; - } - } - m_file = new QFile(m_localFileName); - } + m_errorString.clear(); + + if (!m_url.isValid()) { + m_file = new QFile(); + return; + } + + // We assume for simplicity that s_tempDir is not empty, this is the + // case because a TikzPreviewController object is created at startup + // and in its constructor setTempDir() is called. + Q_ASSERT_X(!s_tempDir.isEmpty(), "loading a file", + "File::setTempDir(const QString &dirName) must be called before constructing any " + "File object"); + m_localFileName = m_url.isLocalFile() ? m_url.path() : s_tempDir + m_url.fileName(); + + if (m_openMode == WriteOnly) { + // m_file = new KSaveFile(m_localFileName); + m_file = new QFile(m_localFileName); + } else if (m_openMode == ReadOnly) { + if (!m_url.isLocalFile() && File::fileExists(m_url)) { + KIO::Job *job = KIO::file_copy(m_url, QUrl::fromLocalFile(m_localFileName), -1, + KIO::Overwrite | KIO::HideProgressInfo); + KJobWidgets::setWindow(job, s_mainWidget); + if (!job->exec()) { + m_errorString = tr("Could not copy \"%1\" to temporary file \"%2\".") + .arg(m_url.toDisplayString()) + .arg(m_localFileName); + return; + } + } + m_file = new QFile(m_localFileName); + } } File::~File() { - close(); - delete m_file; + close(); + delete m_file; } bool File::open(const QFile::OpenMode &mode) { - if (m_openMode == WriteOnly) - { - m_errorString.clear(); - //return dynamic_cast(m_file)->open(); // XXX cannot use qobject_cast because QSaveFile doesn't have the Q_OBJECT macro - return m_file->open( QFile::WriteOnly ); // XXX cannot use qobject_cast because QSaveFile doesn't have the Q_OBJECT macro - } - else if (m_openMode == ReadOnly) - { - if (!m_errorString.isEmpty()) // when the file is not a local file and copying the file to a local file using KIO failed - return false; - return m_file->open(QFile::ReadOnly | mode); - } - return false; + if (m_openMode == WriteOnly) { + m_errorString.clear(); + // return dynamic_cast(m_file)->open(); // XXX cannot use qobject_cast because + // QSaveFile doesn't have the Q_OBJECT macro + return m_file->open(QFile::WriteOnly); // XXX cannot use qobject_cast because QSaveFile + // doesn't have the Q_OBJECT macro + } else if (m_openMode == ReadOnly) { + if (!m_errorString.isEmpty()) // when the file is not a local file and copying the file to a + // local file using KIO failed + return false; + return m_file->open(QFile::ReadOnly | mode); + } + return false; } bool File::close() { - m_errorString.clear(); - - if (m_openMode == WriteOnly) - { - //if (!dynamic_cast(m_file)->finalize()) // XXX cannot use qobject_cast because QSaveFile doesn't have the Q_OBJECT macro - // return false; - m_file->close(); - return true; - } - m_file->close(); - - if (m_openMode == WriteOnly && !m_url.isLocalFile()) - { - KIO::Job *job = KIO::file_copy(QUrl::fromLocalFile(m_localFileName), m_url, -1, KIO::Overwrite | KIO::HideProgressInfo); - KJobWidgets::setWindow(job, s_mainWidget); - if (!job->exec()) - { - m_errorString = tr("Could not copy temporary file \"%1\" to \"%2\".").arg(m_localFileName).arg(m_url.toDisplayString()); - return false; - } - } - return true; + m_errorString.clear(); + + if (m_openMode == WriteOnly) { + // if (!dynamic_cast(m_file)->finalize()) // XXX cannot use qobject_cast because + // QSaveFile doesn't have the Q_OBJECT macro return false; + m_file->close(); + return true; + } + m_file->close(); + + if (m_openMode == WriteOnly && !m_url.isLocalFile()) { + KIO::Job *job = KIO::file_copy(QUrl::fromLocalFile(m_localFileName), m_url, -1, + KIO::Overwrite | KIO::HideProgressInfo); + KJobWidgets::setWindow(job, s_mainWidget); + if (!job->exec()) { + m_errorString = tr("Could not copy temporary file \"%1\" to \"%2\".") + .arg(m_localFileName) + .arg(m_url.toDisplayString()); + return false; + } + } + return true; } /* @@ -154,54 +148,57 @@ bool File::close() /* void File::showJobError(KJob *job) { - if (job->error() != 0) - { - KIO::JobUiDelegate *ui = static_cast(job)->ui(); - if (!ui) - { - qCritical() << "Saving failed; job->ui() is null."; - return; - } - ui->setWindow(s_mainWidget); - ui->showErrorMessage(); - } + if (job->error() != 0) + { + KIO::JobUiDelegate *ui = static_cast(job)->ui(); + if (!ui) + { + qCritical() << "Saving failed; job->ui() is null."; + return; + } + ui->setWindow(s_mainWidget); + ui->showErrorMessage(); + } } */ bool File::copy(const QUrl &fromUrl, const QUrl &toUrl) { - KIO::Job *job = KIO::file_copy(fromUrl, toUrl, -1, KIO::Overwrite | KIO::HideProgressInfo); - KJobWidgets::setWindow(job, s_mainWidget); - return job->exec();; + KIO::Job *job = KIO::file_copy(fromUrl, toUrl, -1, KIO::Overwrite | KIO::HideProgressInfo); + KJobWidgets::setWindow(job, s_mainWidget); + return job->exec(); + ; } /*! * This function sets the main widget which will be used as a parent for all * KIO dialogs used for copying remote files in the KDE version. This function * \b must be called prior to creating any File object. - * \param widget a QWidget which will be the parent widget for the KIO dialogs, typically this is the main window + * \param widget a QWidget which will be the parent widget for the KIO dialogs, typically this is + * the main window */ void File::setMainWidget(QWidget *widget) { - s_mainWidget = widget; + s_mainWidget = widget; } /*! * This function sets the temporary directory in which all remote files will * be copied by KIO in order to use them locally. This function * \b must be called prior to creating any File object. - * \param dirName the name of the temporary directory in which the local versions of the remote files are stored + * \param dirName the name of the temporary directory in which the local versions of the remote + * files are stored */ void File::setTempDir(const QString &dirName) { - s_tempDir = dirName; + s_tempDir = dirName; } #else -//#include -//#include -#include +// #include +// #include +# include /*! * Constructs a File object. @@ -211,8 +208,8 @@ void File::setTempDir(const QString &dirName) File::File(const QString &fileName, const OpenMode &mode) { - m_openMode = mode; - m_file = new QFile(fileName); + m_openMode = mode; + m_file = new QFile(fileName); } /*! @@ -223,14 +220,14 @@ File::File(const QString &fileName, const OpenMode &mode) File::File(const QUrl &url, const OpenMode &mode) { - m_openMode = mode; - m_file = new QFile(Url(url).path()); + m_openMode = mode; + m_file = new QFile(Url(url).path()); } File::~File() { - close(); - delete m_file; + close(); + delete m_file; } /*! @@ -242,11 +239,11 @@ File::~File() bool File::open(const QFile::OpenMode &mode) { - if (m_openMode == WriteOnly) - return m_file->open(QFile::WriteOnly | mode); - else if (m_openMode == ReadOnly) - return m_file->open(QFile::ReadOnly | mode); - return false; + if (m_openMode == WriteOnly) + return m_file->open(QFile::WriteOnly | mode); + else if (m_openMode == ReadOnly) + return m_file->open(QFile::ReadOnly | mode); + return false; } /*! @@ -256,8 +253,8 @@ bool File::open(const QFile::OpenMode &mode) bool File::close() { - m_file->close(); - return true; + m_file->close(); + return true; } /*! @@ -270,17 +267,16 @@ bool File::close() bool File::copy(const QUrl &fromUrl, const QUrl &toUrl) { - const QString toFileName = Url(toUrl).path(); - if (QFileInfo(toFileName).exists() && !QFile::remove(toFileName)) - { -// QMessageBox::critical(s_mainWidget, QCoreApplication::applicationName(), -// tr("The file \"%1\" could not be overwritten").arg(toFileName)); - return false; - } -// if (!QFile::copy(Url(fromUrl).path(), Url(toUrl).path())) -// QMessageBox::critical(s_mainWidget, QCoreApplication::applicationName(), -// tr("The file \"%1\" could not be copied to").arg(toFileName)); - return QFile::copy(Url(fromUrl).path(), toFileName); + const QString toFileName = Url(toUrl).path(); + if (QFileInfo(toFileName).exists() && !QFile::remove(toFileName)) { + // QMessageBox::critical(s_mainWidget, QCoreApplication::applicationName(), + // tr("The file \"%1\" could not be overwritten").arg(toFileName)); + return false; + } + // if (!QFile::copy(Url(fromUrl).path(), Url(toUrl).path())) + // QMessageBox::critical(s_mainWidget, QCoreApplication::applicationName(), + // tr("The file \"%1\" could not be copied to").arg(toFileName)); + return QFile::copy(Url(fromUrl).path(), toFileName); } #endif @@ -310,7 +306,7 @@ bool File::copy(const QUrl &fromUrl, const QUrl &toUrl) QFile *File::file() { - return m_file; + return m_file; } /*! @@ -320,7 +316,7 @@ QFile *File::file() QString File::errorString() const { - if (!m_errorString.isEmpty()) - return m_errorString; - return m_file->errorString(); + if (!m_errorString.isEmpty()) + return m_errorString; + return m_file->errorString(); } diff --git a/common/utils/file.h b/common/utils/file.h index 75db572..ca76412 100644 --- a/common/utils/file.h +++ b/common/utils/file.h @@ -21,7 +21,7 @@ #include #include -//#include +// #include #include #ifdef KTIKZ_USE_KDE @@ -84,53 +84,52 @@ class KJob; class File : public QObject { - Q_OBJECT + Q_OBJECT public: - /*! - * This enum is used with the constructor to describe the mode in which - * the file will be opened. - */ - enum OpenMode - { - ReadOnly, /*!= 0) // filter is a string like "text/x-pgf text/x-tex" - { - const QStringList mimeTypeList = filter.split(QLatin1Char(' ')); - for (int i = 0; i < mimeTypeList.size(); ++i) - { - if (i > 0) - parsedFilter += QLatin1String(";;"); - if (mimeTypeList.at(i) == QLatin1String("text/x-pgf")) - parsedFilter += QCoreApplication::translate("FileDialog", "PGF document", "filter") + QLatin1String(" (*.pgf *.tikz *.tex)"); - else if (mimeTypeList.at(i) == QLatin1String("image/x-eps")) - parsedFilter += QCoreApplication::translate("FileDialog", "EPS image", "filter") + QLatin1String(" (*.eps)"); - else if (mimeTypeList.at(i) == QLatin1String("application/pdf")) - parsedFilter += QCoreApplication::translate("FileDialog", "PDF document", "filter") + QLatin1String(" (*.pdf)"); - else if (mimeTypeList.at(i).startsWith(QLatin1String("image/"))) - { - const QString mimeType = mimeTypeList.at(i).mid(6); - parsedFilter += QCoreApplication::translate("FileDialog", "%1 image", "filter").arg(mimeType.toUpper()) + QLatin1String(" (*.") + mimeType + QLatin1Char(')'); - } - } - } - else if (filter.indexOf(QLatin1Char('|')) >= 0) // filter is a string like "*.pgf *.tikz|PGF document\n*.tex|TeX document", we assume that in this case '/' doesn't appear in filter - { - const QStringList filterList = filter.split(QLatin1Char('\n')); - for (int i = 0; i < filterList.size(); ++i) - { - const QStringList filterItems = filterList.at(i).split(QLatin1Char('|')); - if (i > 0) - parsedFilter += QLatin1String(";;"); - parsedFilter += filterItems.at(1) + QLatin1String(" (") + filterItems.at(0) + QLatin1Char(')'); - } - } - if (!parsedFilter.isEmpty()) - parsedFilter += QLatin1String(";;"); - parsedFilter += QCoreApplication::translate("FileDialog", "All files", "filter") + QLatin1String(" (*)"); - return parsedFilter; + QString parsedFilter; + if (filter.indexOf(QLatin1Char('/')) >= 0) // filter is a string like "text/x-pgf text/x-tex" + { + const QStringList mimeTypeList = filter.split(QLatin1Char(' ')); + for (int i = 0; i < mimeTypeList.size(); ++i) { + if (i > 0) + parsedFilter += QLatin1String(";;"); + if (mimeTypeList.at(i) == QLatin1String("text/x-pgf")) + parsedFilter += QCoreApplication::translate("FileDialog", "PGF document", "filter") + + QLatin1String(" (*.pgf *.tikz *.tex)"); + else if (mimeTypeList.at(i) == QLatin1String("image/x-eps")) + parsedFilter += QCoreApplication::translate("FileDialog", "EPS image", "filter") + + QLatin1String(" (*.eps)"); + else if (mimeTypeList.at(i) == QLatin1String("application/pdf")) + parsedFilter += QCoreApplication::translate("FileDialog", "PDF document", "filter") + + QLatin1String(" (*.pdf)"); + else if (mimeTypeList.at(i).startsWith(QLatin1String("image/"))) { + const QString mimeType = mimeTypeList.at(i).mid(6); + parsedFilter += QCoreApplication::translate("FileDialog", "%1 image", "filter") + .arg(mimeType.toUpper()) + + QLatin1String(" (*.") + mimeType + QLatin1Char(')'); + } + } + } else if (filter.indexOf(QLatin1Char('|')) + >= 0) // filter is a string like "*.pgf *.tikz|PGF document\n*.tex|TeX document", we + // assume that in this case '/' doesn't appear in filter + { + const QStringList filterList = filter.split(QLatin1Char('\n')); + for (int i = 0; i < filterList.size(); ++i) { + const QStringList filterItems = filterList.at(i).split(QLatin1Char('|')); + if (i > 0) + parsedFilter += QLatin1String(";;"); + parsedFilter += + filterItems.at(1) + QLatin1String(" (") + filterItems.at(0) + QLatin1Char(')'); + } + } + if (!parsedFilter.isEmpty()) + parsedFilter += QLatin1String(";;"); + parsedFilter += QCoreApplication::translate("FileDialog", "All files", "filter") + + QLatin1String(" (*)"); + return parsedFilter; } /*! @@ -100,16 +105,23 @@ static QString getParsedFilter(const QString &filter) * \param parent the parent widget for which the file dialog will be a modal dialog * \param caption the title of the file dialog * \param dir starting directory; if dir includes a file name, the file will be selected - * \param filter a list of filters separated by '\\n'; every filter entry is defined through \c namefilter|text \c to \c display. If no '|' is found in the expression, just the namefilter is shown. In the Qt-only version the filter "All files (*)" is automatically appended to cover the case in which the "Filter" entry of the dialog cannot be cleared (as in KDE's file dialog). Alternatively, a list of mimetypes separated by a space can be given. For better consistency across applications in a KDE environment, it is recommended to use the latter option. - * \return an url specifying the file selected by the user in the file dialog + * \param filter a list of filters separated by '\\n'; every filter entry is defined through \c + * namefilter|text \c to \c display. If no '|' is found in the expression, just the namefilter is + * shown. In the Qt-only version the filter "All files (*)" is automatically appended to cover the + * case in which the "Filter" entry of the dialog cannot be cleared (as in KDE's file dialog). + * Alternatively, a list of mimetypes separated by a space can be given. For better consistency + * across applications in a KDE environment, it is recommended to use the latter option. \return an + * url specifying the file selected by the user in the file dialog */ -Url FileDialog::getOpenUrl(QWidget *parent, const QString &caption, const Url &dir, const QString &filter) +Url FileDialog::getOpenUrl(QWidget *parent, const QString &caption, const Url &dir, + const QString &filter) { - const QUrl openFileName = QFileDialog::getOpenFileUrl(parent, caption, dir, getParsedFilter(filter)); - if (openFileName.isEmpty()) - return Url(); - return Url(openFileName); + const QUrl openFileName = + QFileDialog::getOpenFileUrl(parent, caption, dir, getParsedFilter(filter)); + if (openFileName.isEmpty()) + return Url(); + return Url(openFileName); } /*! @@ -143,15 +155,22 @@ Url FileDialog::getOpenUrl(QWidget *parent, const QString &caption, const Url &d * \param parent the parent widget for which the file dialog will be a modal dialog * \param caption the title of the file dialog * \param dir starting directory; if dir includes a file name, the file will be selected - * \param filter a list of filters separated by '\\n'; every filter entry is defined through \c namefilter|text \c to \c display. If no '|' is found in the expression, just the namefilter is shown. In the Qt-only version the filter "All files (*)" is automatically appended to cover the case in which the "Filter" entry of the dialog cannot be cleared (as in KDE's file dialog). Alternatively, a list of mimetypes separated by a space can be given. For better consistency across applications in a KDE environment, it is recommended to use the latter option. - * \return an url specifying the file selected by the user in the file dialog + * \param filter a list of filters separated by '\\n'; every filter entry is defined through \c + * namefilter|text \c to \c display. If no '|' is found in the expression, just the namefilter is + * shown. In the Qt-only version the filter "All files (*)" is automatically appended to cover the + * case in which the "Filter" entry of the dialog cannot be cleared (as in KDE's file dialog). + * Alternatively, a list of mimetypes separated by a space can be given. For better consistency + * across applications in a KDE environment, it is recommended to use the latter option. \return an + * url specifying the file selected by the user in the file dialog */ -Url FileDialog::getSaveUrl(QWidget *parent, const QString &caption, const Url &dir, const QString &filter) +Url FileDialog::getSaveUrl(QWidget *parent, const QString &caption, const Url &dir, + const QString &filter) { - const QUrl saveAsFileName = QFileDialog::getSaveFileUrl(parent, caption, dir, getParsedFilter(filter)); - if (saveAsFileName.isEmpty()) - return Url(); + const QUrl saveAsFileName = + QFileDialog::getSaveFileUrl(parent, caption, dir, getParsedFilter(filter)); + if (saveAsFileName.isEmpty()) + return Url(); - return Url(saveAsFileName); + return Url(saveAsFileName); } diff --git a/common/utils/filedialog.h b/common/utils/filedialog.h index 239b1f4..1c5ce6a 100644 --- a/common/utils/filedialog.h +++ b/common/utils/filedialog.h @@ -23,7 +23,6 @@ #include - /*! * \brief Provides a dialog to select an URL for opening or saving. * @@ -41,10 +40,16 @@ class FileDialog : public QFileDialog { public: - explicit FileDialog(QWidget *parent = 0, const QString &caption = QString(), const QString &directory = QString(), const QString &filter = QString()) : QFileDialog(parent, caption, directory, filter) {} - - static Url getOpenUrl(QWidget *parent = 0, const QString &caption = QString(), const Url &dir = Url(), const QString &filter = QString()); - static Url getSaveUrl(QWidget *parent = 0, const QString &caption = QString(), const Url &dir = Url(), const QString &filter = QString()); + explicit FileDialog(QWidget *parent = 0, const QString &caption = QString(), + const QString &directory = QString(), const QString &filter = QString()) + : QFileDialog(parent, caption, directory, filter) + { + } + + static Url getOpenUrl(QWidget *parent = 0, const QString &caption = QString(), + const Url &dir = Url(), const QString &filter = QString()); + static Url getSaveUrl(QWidget *parent = 0, const QString &caption = QString(), + const Url &dir = Url(), const QString &filter = QString()); }; #endif diff --git a/common/utils/fontdialog.h b/common/utils/fontdialog.h index 6068daf..8979c78 100644 --- a/common/utils/fontdialog.h +++ b/common/utils/fontdialog.h @@ -24,12 +24,12 @@ class FontDialog : public QFontDialog { public: - FontDialog(QWidget *parent) : QFontDialog(parent) {} + FontDialog(QWidget *parent) : QFontDialog(parent) { } - static QFont getFont(bool *ok, const QFont &font, QWidget *parent) - { - return QFontDialog::getFont(ok, font, parent); - } + static QFont getFont(bool *ok, const QFont &font, QWidget *parent) + { + return QFontDialog::getFont(ok, font, parent); + } }; #endif diff --git a/common/utils/globallocale.cpp b/common/utils/globallocale.cpp index 742ae76..19d37b2 100644 --- a/common/utils/globallocale.cpp +++ b/common/utils/globallocale.cpp @@ -22,16 +22,15 @@ QString GlobalLocale::decimalSymbol() { - return QLocale::system().decimalPoint(); + return QLocale::system().decimalPoint(); } QString GlobalLocale::formatNumber(double num, int precision) { - return QLocale::system().toString(num, 'f', precision); + return QLocale::system().toString(num, 'f', precision); } double GlobalLocale::readNumber(const QString &str) { - return str.toDouble(); + return str.toDouble(); } - diff --git a/common/utils/globallocale.h b/common/utils/globallocale.h index a431e3c..1e955ba 100644 --- a/common/utils/globallocale.h +++ b/common/utils/globallocale.h @@ -24,9 +24,9 @@ class GlobalLocale { public: - static QString decimalSymbol(); - static QString formatNumber(double num, int precision = -1); - static double readNumber(const QString &str); + static QString decimalSymbol(); + static QString formatNumber(double num, int precision = -1); + static double readNumber(const QString &str); }; #endif diff --git a/common/utils/icon.h b/common/utils/icon.h index 2b27d2f..d0581b8 100644 --- a/common/utils/icon.h +++ b/common/utils/icon.h @@ -24,14 +24,18 @@ class Icon : public QIcon { public: -// Check why second option might make more sense -//#ifdef KTIKZ_USE_DESKTOP_ICONS - explicit Icon(const QString &iconName) : QIcon(QIcon::fromTheme(iconName, QIcon(QLatin1String(":/icons/") + iconName + QLatin1String(".png")))) {} -//#else -// explicit Icon(const QString &iconName) : QIcon(QLatin1String(":/icons/") + iconName + QLatin1String(".png")) {} // faster than the above -//#endif - explicit Icon(const QIcon ©) : QIcon(copy) {} - Icon() : QIcon() {} + // Check why second option might make more sense + // #ifdef KTIKZ_USE_DESKTOP_ICONS + explicit Icon(const QString &iconName) + : QIcon(QIcon::fromTheme( + iconName, QIcon(QLatin1String(":/icons/") + iconName + QLatin1String(".png")))) + { + } + // #else + // explicit Icon(const QString &iconName) : QIcon(QLatin1String(":/icons/") + iconName + + //QLatin1String(".png")) {} // faster than the above #endif + explicit Icon(const QIcon ©) : QIcon(copy) { } + Icon() : QIcon() { } }; #endif diff --git a/common/utils/lineedit.cpp b/common/utils/lineedit.cpp index 8a05079..ccc3ab2 100644 --- a/common/utils/lineedit.cpp +++ b/common/utils/lineedit.cpp @@ -11,79 +11,78 @@ #include "lineedit.h" #ifdef KTIKZ_USE_KDE -LineEdit::LineEdit(const QString &text, QWidget *parent) - : KLineEdit(text, parent) +LineEdit::LineEdit(const QString &text, QWidget *parent) : KLineEdit(text, parent) { - setClearButtonEnabled(true); + setClearButtonEnabled(true); } -LineEdit::LineEdit(QWidget *parent) - : KLineEdit(parent) +LineEdit::LineEdit(QWidget *parent) : KLineEdit(parent) { - setClearButtonEnabled(true); + setClearButtonEnabled(true); } #else -#include -#include +# include +# include -#include "urlcompletion.h" +# include "urlcompletion.h" -LineEdit::LineEdit(const QString &text, QWidget *parent) - : QLineEdit(parent) +LineEdit::LineEdit(const QString &text, QWidget *parent) : QLineEdit(parent) { - init(); - setText(text); + init(); + setText(text); } -LineEdit::LineEdit(QWidget *parent) - : QLineEdit(parent) +LineEdit::LineEdit(QWidget *parent) : QLineEdit(parent) { - init(); + init(); } void LineEdit::init() { - m_clearButton = new QToolButton(this); - const QPixmap pixmap(QLatin1String(":/icons/edit-clear-locationbar-rtl.png")); - m_clearButton->setIcon(QIcon(pixmap)); - m_clearButton->setIconSize(pixmap.size()); - m_clearButton->setCursor(Qt::ArrowCursor); - m_clearButton->setStyleSheet(QLatin1String("QToolButton { border: none; padding: 0px; }")); - m_clearButton->setToolTip(tr("Clear input field")); - m_clearButton->hide(); - connect(m_clearButton, SIGNAL(clicked()), this, SLOT(clear())); - connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateClearButton(QString))); -// const int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); -// setStyleSheet(QString("QLineEdit { padding-right: %1px; width: %2px; height: %3px; }") -// .arg(m_clearButton->sizeHint().width() + frameWidth + 1) -// .arg(sizeHint().width()) -// .arg(sizeHint().height())); - setStyleSheet(QString(QLatin1String("QLineEdit { padding-right: %1px; }")) - .arg(m_clearButton->sizeHint().width() + style()->pixelMetric(QStyle::PM_DefaultFrameWidth) + 1)); + m_clearButton = new QToolButton(this); + const QPixmap pixmap(QLatin1String(":/icons/edit-clear-locationbar-rtl.png")); + m_clearButton->setIcon(QIcon(pixmap)); + m_clearButton->setIconSize(pixmap.size()); + m_clearButton->setCursor(Qt::ArrowCursor); + m_clearButton->setStyleSheet(QLatin1String("QToolButton { border: none; padding: 0px; }")); + m_clearButton->setToolTip(tr("Clear input field")); + m_clearButton->hide(); + connect(m_clearButton, SIGNAL(clicked()), this, SLOT(clear())); + connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateClearButton(QString))); + // const int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + // setStyleSheet(QString("QLineEdit { padding-right: %1px; width: %2px; height: %3px; }") + // .arg(m_clearButton->sizeHint().width() + frameWidth + 1) + // .arg(sizeHint().width()) + // .arg(sizeHint().height())); + setStyleSheet(QString(QLatin1String("QLineEdit { padding-right: %1px; }")) + .arg(m_clearButton->sizeHint().width() + + style()->pixelMetric(QStyle::PM_DefaultFrameWidth) + 1)); } QSize LineEdit::sizeHint() const { - const QSize msz = QLineEdit::sizeHint(); - const int minimumHeight = m_clearButton->sizeHint().height() + style()->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2; - return QSize(qMax(msz.width(), minimumHeight + 2), qMax(msz.height(), minimumHeight)); + const QSize msz = QLineEdit::sizeHint(); + const int minimumHeight = m_clearButton->sizeHint().height() + + style()->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2; + return QSize(qMax(msz.width(), minimumHeight + 2), qMax(msz.height(), minimumHeight)); } void LineEdit::resizeEvent(QResizeEvent *event) { - const QSize sz = m_clearButton->sizeHint(); - m_clearButton->move(rect().right() - style()->pixelMetric(QStyle::PM_DefaultFrameWidth) - sz.width(), - (rect().bottom() + 1 - sz.height()) / 2); - QLineEdit::resizeEvent(event); + const QSize sz = m_clearButton->sizeHint(); + m_clearButton->move(rect().right() - style()->pixelMetric(QStyle::PM_DefaultFrameWidth) + - sz.width(), + (rect().bottom() + 1 - sz.height()) / 2); + QLineEdit::resizeEvent(event); } void LineEdit::updateClearButton(const QString &text) { - m_clearButton->setVisible(!text.isEmpty()); + m_clearButton->setVisible(!text.isEmpty()); } void LineEdit::setCompletionObject(UrlCompletion *urlCompletion) { - setCompleter(urlCompletion); + setCompleter(urlCompletion); } #endif diff --git a/common/utils/lineedit.h b/common/utils/lineedit.h index 00305bd..833403d 100644 --- a/common/utils/lineedit.h +++ b/common/utils/lineedit.h @@ -12,43 +12,43 @@ #define KTIKZ_LINEEDIT_H #ifdef KTIKZ_USE_KDE -#include +# include class LineEdit : public KLineEdit { - Q_OBJECT + Q_OBJECT public: - explicit LineEdit(const QString &text, QWidget *parent = 0); - explicit LineEdit(QWidget *parent = 0); + explicit LineEdit(const QString &text, QWidget *parent = 0); + explicit LineEdit(QWidget *parent = 0); }; #else -#include -#include +# include +# include class QToolButton; class UrlCompletion; class LineEdit : public QLineEdit { - Q_OBJECT + Q_OBJECT public: - explicit LineEdit(const QString &text, QWidget *parent = 0); - explicit LineEdit(QWidget *parent = 0); - virtual QSize sizeHint() const; - void setCompletionObject(UrlCompletion *urlCompletion); + explicit LineEdit(const QString &text, QWidget *parent = 0); + explicit LineEdit(QWidget *parent = 0); + virtual QSize sizeHint() const; + void setCompletionObject(UrlCompletion *urlCompletion); protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event); private Q_SLOTS: - void updateClearButton(const QString &text); + void updateClearButton(const QString &text); private: - void init(); + void init(); - QToolButton *m_clearButton; + QToolButton *m_clearButton; }; #endif diff --git a/common/utils/messagebox.cpp b/common/utils/messagebox.cpp index b9cb0fe..b0c4f5b 100644 --- a/common/utils/messagebox.cpp +++ b/common/utils/messagebox.cpp @@ -19,66 +19,68 @@ #include "messagebox.h" #ifdef KTIKZ_USE_KDE -#include +# include -int MessageBox::questionYesNo(QWidget *parent, const QString &text, const QString &caption, const QString &yesButtonText, const QString &noButtonText) +int MessageBox::questionYesNo(QWidget *parent, const QString &text, const QString &caption, + const QString &yesButtonText, const QString &noButtonText) { - int result; - if (!yesButtonText.isEmpty()) - { - if (!noButtonText.isEmpty()) - result = KMessageBox::questionYesNo(parent, text, caption, KGuiItem(yesButtonText, QLatin1String("dialog-ok")), KGuiItem(noButtonText, QLatin1String("process-stop"))); - else - result = KMessageBox::questionYesNo(parent, text, caption, KGuiItem(yesButtonText, QLatin1String("dialog-ok"))); - } - else - result = KMessageBox::questionYesNo(parent, text, caption); + int result; + if (!yesButtonText.isEmpty()) { + if (!noButtonText.isEmpty()) + result = KMessageBox::questionYesNo( + parent, text, caption, KGuiItem(yesButtonText, QLatin1String("dialog-ok")), + KGuiItem(noButtonText, QLatin1String("process-stop"))); + else + result = KMessageBox::questionYesNo( + parent, text, caption, KGuiItem(yesButtonText, QLatin1String("dialog-ok"))); + } else + result = KMessageBox::questionYesNo(parent, text, caption); - return (result == KMessageBox::Yes) ? Yes : No; + return (result == KMessageBox::Yes) ? Yes : No; } void MessageBox::sorry(QWidget *parent, const QString &text, const QString &caption) { - KMessageBox::sorry(parent, text, caption); + KMessageBox::sorry(parent, text, caption); } void MessageBox::error(QWidget *parent, const QString &text, const QString &caption) { - KMessageBox::error(parent, text, caption); + KMessageBox::error(parent, text, caption); } #else -#include -#include +# include +# include -int MessageBox::questionYesNo(QWidget *parent, const QString &text, const QString &caption, const QString &yesButtonText, const QString &noButtonText) +int MessageBox::questionYesNo(QWidget *parent, const QString &text, const QString &caption, + const QString &yesButtonText, const QString &noButtonText) { - QMessageBox::StandardButton result; - if (!yesButtonText.isEmpty()) - { - QMessageBox msgBox(QMessageBox::Question, caption, text, QMessageBox::NoButton, parent); - QPushButton *yesButton = msgBox.addButton(yesButtonText, QMessageBox::YesRole); - if (!noButtonText.isEmpty()) - msgBox.addButton(noButtonText, QMessageBox::NoRole); - else - msgBox.addButton(QMessageBox::No); - msgBox.setDefaultButton(yesButton); + QMessageBox::StandardButton result; + if (!yesButtonText.isEmpty()) { + QMessageBox msgBox(QMessageBox::Question, caption, text, QMessageBox::NoButton, parent); + QPushButton *yesButton = msgBox.addButton(yesButtonText, QMessageBox::YesRole); + if (!noButtonText.isEmpty()) + msgBox.addButton(noButtonText, QMessageBox::NoRole); + else + msgBox.addButton(QMessageBox::No); + msgBox.setDefaultButton(yesButton); - msgBox.exec(); - return (msgBox.clickedButton() == yesButton) ? Yes : No; - } - else - result = QMessageBox::question(parent, caption, text, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + msgBox.exec(); + return (msgBox.clickedButton() == yesButton) ? Yes : No; + } else + result = QMessageBox::question(parent, caption, text, QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes); - return (result == QMessageBox::Yes) ? Yes : No; + return (result == QMessageBox::Yes) ? Yes : No; } void MessageBox::sorry(QWidget *parent, const QString &text, const QString &caption) { - QMessageBox::warning(parent, caption, text); + QMessageBox::warning(parent, caption, text); } void MessageBox::error(QWidget *parent, const QString &text, const QString &caption) { - QMessageBox::critical(parent, caption, text); + QMessageBox::critical(parent, caption, text); } #endif diff --git a/common/utils/messagebox.h b/common/utils/messagebox.h index c5d8b1b..4bee358 100644 --- a/common/utils/messagebox.h +++ b/common/utils/messagebox.h @@ -25,18 +25,14 @@ class QWidget; class MessageBox { public: - enum ButtonCode - { - Ok = 1, - Cancel = 2, - Yes = 3, - No = 4, - Continue = 5 - }; + enum ButtonCode { Ok = 1, Cancel = 2, Yes = 3, No = 4, Continue = 5 }; - static int questionYesNo(QWidget *parent, const QString &text, const QString &caption = QString(), const QString &yesButtonText = QString(), const QString &noButtonText = QString()); - static void sorry(QWidget *parent, const QString &text, const QString &caption = QString()); - static void error(QWidget *parent, const QString &text, const QString &caption = QString()); + static int questionYesNo(QWidget *parent, const QString &text, + const QString &caption = QString(), + const QString &yesButtonText = QString(), + const QString &noButtonText = QString()); + static void sorry(QWidget *parent, const QString &text, const QString &caption = QString()); + static void error(QWidget *parent, const QString &text, const QString &caption = QString()); }; #endif diff --git a/common/utils/pagedialog.cpp b/common/utils/pagedialog.cpp index 4dfc110..aa27e90 100644 --- a/common/utils/pagedialog.cpp +++ b/common/utils/pagedialog.cpp @@ -18,142 +18,144 @@ #include "pagedialog.h" #ifdef KTIKZ_USE_KDE -#include +# include PageDialog::PageDialog(QWidget *parent) : KPageDialog(parent) { - setFaceType(List); - setStandardButtons(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Apply); - QPushButton *okButton = buttonBox()->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox ()->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(accept())); - connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); + setFaceType(List); + setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Help + | QDialogButtonBox::Apply); + QPushButton *okButton = buttonBox()->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox()->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(accept())); + connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); } void PageDialog::addPage(QWidget *widget, const QString &title, const QString &iconName) { - QString titleString = title; - titleString.remove(QLatin1Char('&')); + QString titleString = title; + titleString.remove(QLatin1Char('&')); - KPageWidgetItem *page = new KPageWidgetItem(widget, titleString); - page->setHeader(titleString); - page->setIcon(QIcon::fromTheme(iconName)); - KPageDialog::addPage(page); + KPageWidgetItem *page = new KPageWidgetItem(widget, titleString); + page->setHeader(titleString); + page->setIcon(QIcon::fromTheme(iconName)); + KPageDialog::addPage(page); } #else -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "icon.h" +# include +# include +# include +# include +# include +# include +# include +# include +# include + +# include +# include +# include + +# include "icon.h" PageDialog::PageDialog(QWidget *parent) : QDialog(parent) { - m_iconWidth = 0; - - // add What's this, OK, Cancel buttons - QDialogButtonBox *buttonBox = new QDialogButtonBox; - QAction *whatsThisAction = QWhatsThis::createAction(this); - whatsThisAction->setIcon(Icon(QLatin1String("help-contextual"))); - QToolButton *whatsThisButton = new QToolButton(this); - whatsThisButton->setDefaultAction(whatsThisAction); - whatsThisButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored); - buttonBox->addButton(whatsThisButton, QDialogButtonBox::HelpRole); - buttonBox->addButton(QDialogButtonBox::Ok); - buttonBox->addButton(QDialogButtonBox::Cancel); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addWidget(centerWidget()); - mainLayout->addWidget(buttonBox); - setLayout(mainLayout); + m_iconWidth = 0; + + // add What's this, OK, Cancel buttons + QDialogButtonBox *buttonBox = new QDialogButtonBox; + QAction *whatsThisAction = QWhatsThis::createAction(this); + whatsThisAction->setIcon(Icon(QLatin1String("help-contextual"))); + QToolButton *whatsThisButton = new QToolButton(this); + whatsThisButton->setDefaultAction(whatsThisAction); + whatsThisButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored); + buttonBox->addButton(whatsThisButton, QDialogButtonBox::HelpRole); + buttonBox->addButton(QDialogButtonBox::Ok); + buttonBox->addButton(QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(centerWidget()); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); } QWidget *PageDialog::centerWidget() { - // create list - m_pagesListWidget = new QListWidget; - m_pagesListWidget->setViewMode(QListView::IconMode); - m_pagesListWidget->setMovement(QListView::Static); - m_pagesListWidget->setFlow(QListView::TopToBottom); - m_pagesListWidget->setWordWrap(true); - m_pagesListWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); - - // create title - QFrame *titleFrame = new QFrame(this); - titleFrame->setFrameShape(QFrame::Box); - m_pagesTitleLabel = new QLabel(titleFrame); - m_pagesTitleLabel->setStyleSheet(QLatin1String("QLabel { font-weight: bold; }")); - QGridLayout *titleLayout = new QGridLayout(titleFrame); - titleLayout->setColumnStretch(0, 1); - titleLayout->setMargin(6); - titleLayout->addWidget(m_pagesTitleLabel); - - // add pages - m_pagesStackedWidget = new QStackedWidget; - connect(m_pagesListWidget, SIGNAL(currentRowChanged(int)), m_pagesStackedWidget, SLOT(setCurrentIndex(int))); - connect(m_pagesListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(setCurrentPage(int))); - - QWidget *mainWidget = new QWidget; - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(m_pagesListWidget, 0, 0, 2, 1); - mainLayout->addWidget(titleFrame, 0, 1); - mainLayout->addWidget(m_pagesStackedWidget, 1, 1); - mainWidget->setLayout(mainLayout); - - return mainWidget; + // create list + m_pagesListWidget = new QListWidget; + m_pagesListWidget->setViewMode(QListView::IconMode); + m_pagesListWidget->setMovement(QListView::Static); + m_pagesListWidget->setFlow(QListView::TopToBottom); + m_pagesListWidget->setWordWrap(true); + m_pagesListWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + + // create title + QFrame *titleFrame = new QFrame(this); + titleFrame->setFrameShape(QFrame::Box); + m_pagesTitleLabel = new QLabel(titleFrame); + m_pagesTitleLabel->setStyleSheet(QLatin1String("QLabel { font-weight: bold; }")); + QGridLayout *titleLayout = new QGridLayout(titleFrame); + titleLayout->setColumnStretch(0, 1); + titleLayout->setMargin(6); + titleLayout->addWidget(m_pagesTitleLabel); + + // add pages + m_pagesStackedWidget = new QStackedWidget; + connect(m_pagesListWidget, SIGNAL(currentRowChanged(int)), m_pagesStackedWidget, + SLOT(setCurrentIndex(int))); + connect(m_pagesListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(setCurrentPage(int))); + + QWidget *mainWidget = new QWidget; + QGridLayout *mainLayout = new QGridLayout; + mainLayout->addWidget(m_pagesListWidget, 0, 0, 2, 1); + mainLayout->addWidget(titleFrame, 0, 1); + mainLayout->addWidget(m_pagesStackedWidget, 1, 1); + mainWidget->setLayout(mainLayout); + + return mainWidget; } void PageDialog::setCaption(const QString &caption) { - setWindowTitle(caption); + setWindowTitle(caption); } void PageDialog::setHelp(const QString &anchor) { - Q_UNUSED(anchor); - // not used in Qt-only version + Q_UNUSED(anchor); + // not used in Qt-only version } void PageDialog::addPage(QWidget *widget, const QString &title, const QString &iconName) { - QString titleString = title; - titleString.remove(QLatin1Char('&')); - - QListWidgetItem *item = new QListWidgetItem(Icon(iconName), titleString); - item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); - item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); - m_pagesListWidget->addItem(item); - m_pagesListWidgetItems << item; - - m_iconWidth = qMax(m_iconWidth, m_pagesListWidget->visualItemRect(item).width() + 6); - m_pagesListWidget->setFixedWidth(m_iconWidth); - m_pagesListWidget->setCurrentRow(0); - - // center all labels and icons - for (int i = 0; i < m_pagesListWidget->count(); ++i) - { - QListWidgetItem *item = m_pagesListWidget->item(i); - item->setSizeHint(QSize(m_pagesListWidget->sizeHintForColumn(0), m_pagesListWidget->visualItemRect(item).height())); - } - - m_pagesStackedWidget->addWidget(widget); + QString titleString = title; + titleString.remove(QLatin1Char('&')); + + QListWidgetItem *item = new QListWidgetItem(Icon(iconName), titleString); + item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + m_pagesListWidget->addItem(item); + m_pagesListWidgetItems << item; + + m_iconWidth = qMax(m_iconWidth, m_pagesListWidget->visualItemRect(item).width() + 6); + m_pagesListWidget->setFixedWidth(m_iconWidth); + m_pagesListWidget->setCurrentRow(0); + + // center all labels and icons + for (int i = 0; i < m_pagesListWidget->count(); ++i) { + QListWidgetItem *item = m_pagesListWidget->item(i); + item->setSizeHint(QSize(m_pagesListWidget->sizeHintForColumn(0), + m_pagesListWidget->visualItemRect(item).height())); + } + + m_pagesStackedWidget->addWidget(widget); } void PageDialog::setCurrentPage(int page) { - m_pagesTitleLabel->setText(m_pagesListWidgetItems.at(page)->text()); + m_pagesTitleLabel->setText(m_pagesListWidgetItems.at(page)->text()); } #endif diff --git a/common/utils/pagedialog.h b/common/utils/pagedialog.h index ce658e9..b4ce28c 100644 --- a/common/utils/pagedialog.h +++ b/common/utils/pagedialog.h @@ -20,18 +20,18 @@ #define KTIKZ_PAGEDIALOG_H #ifdef KTIKZ_USE_KDE -#include +# include class PageDialog : public KPageDialog { - Q_OBJECT + Q_OBJECT public: - explicit PageDialog(QWidget *parent = 0); - void addPage(QWidget *widget, const QString &title, const QString &iconName); + explicit PageDialog(QWidget *parent = 0); + void addPage(QWidget *widget, const QString &title, const QString &iconName); }; #else -#include -#include +# include +# include class QLabel; class QListWidget; @@ -40,24 +40,24 @@ class QStackedWidget; class PageDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit PageDialog(QWidget *parent = 0); - void setCaption(const QString &caption); - void setHelp(const QString &anchor); - void addPage(QWidget *widget, const QString &title, const QString &iconName); + explicit PageDialog(QWidget *parent = 0); + void setCaption(const QString &caption); + void setHelp(const QString &anchor); + void addPage(QWidget *widget, const QString &title, const QString &iconName); private Q_SLOTS: - void setCurrentPage(int page); + void setCurrentPage(int page); private: - QWidget *centerWidget(); + QWidget *centerWidget(); - QListWidget *m_pagesListWidget; - QList m_pagesListWidgetItems; - QLabel *m_pagesTitleLabel; - QStackedWidget *m_pagesStackedWidget; - int m_iconWidth; + QListWidget *m_pagesListWidget; + QList m_pagesListWidgetItems; + QLabel *m_pagesTitleLabel; + QStackedWidget *m_pagesStackedWidget; + int m_iconWidth; }; #endif diff --git a/common/utils/printpreviewdialog.cpp b/common/utils/printpreviewdialog.cpp index 7742f53..d23359f 100644 --- a/common/utils/printpreviewdialog.cpp +++ b/common/utils/printpreviewdialog.cpp @@ -28,82 +28,86 @@ #include "toolbar.h" #include "zoomaction.h" -PrintPreviewDialog::PrintPreviewDialog(QPrinter *printer, QWidget *parent) - : QDialog(parent) +PrintPreviewDialog::PrintPreviewDialog(QPrinter *printer, QWidget *parent) : QDialog(parent) { - m_initialized = false; + m_initialized = false; - QVBoxLayout *mainLayout = new QVBoxLayout; + QVBoxLayout *mainLayout = new QVBoxLayout; - m_printPreviewWidget = new QPrintPreviewWidget(printer, this); - connect(m_printPreviewWidget, SIGNAL(paintRequested(QPrinter*)), this, SIGNAL(paintRequested(QPrinter*))); - connect(m_printPreviewWidget, SIGNAL(previewChanged()), this, SLOT(updateZoomFactor())); + m_printPreviewWidget = new QPrintPreviewWidget(printer, this); + connect(m_printPreviewWidget, SIGNAL(paintRequested(QPrinter *)), this, + SIGNAL(paintRequested(QPrinter *))); + connect(m_printPreviewWidget, SIGNAL(previewChanged()), this, SLOT(updateZoomFactor())); - ToolBar *toolBar = new ToolBar(QLatin1String("printpreview_toolbar"), this); - Action *action = new Action(Icon(QLatin1String("zoom-fit-width")), tr("Fit &width"), this, QLatin1String("printpreview_fit_width")); - connect(action, SIGNAL(triggered()), m_printPreviewWidget, SLOT(fitToWidth())); - toolBar->addAction(action); - action = new Action(Icon(QLatin1String("zoom-fit-best")), tr("Fit p&age"), this, QLatin1String("printpreview_fit_page")); - connect(action, SIGNAL(triggered()), m_printPreviewWidget, SLOT(fitInView())); - toolBar->addAction(action); - m_zoomToAction = new ZoomAction(Icon(QLatin1String("zoom-original")), tr("&Zoom"), this, QLatin1String("printpreview_zoom_to")); - connect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); - toolBar->addAction(m_zoomToAction); - toolBar->addAction(StandardAction::zoomIn(this, SLOT(zoomIn()), this)); - toolBar->addAction(StandardAction::zoomOut(this, SLOT(zoomOut()), this)); - action = new Action(Icon(QLatin1String("document-print")), tr("&Print"), this, QLatin1String("printpreview_print")); - connect(action, SIGNAL(triggered()), this, SLOT(print())); - toolBar->addAction(action); - action = new Action(Icon(QLatin1String("window-close")), tr("&Close"), this, QLatin1String("printpreview_close")); - connect(action, SIGNAL(triggered()), this, SLOT(reject())); - toolBar->addAction(action); + ToolBar *toolBar = new ToolBar(QLatin1String("printpreview_toolbar"), this); + Action *action = new Action(Icon(QLatin1String("zoom-fit-width")), tr("Fit &width"), this, + QLatin1String("printpreview_fit_width")); + connect(action, SIGNAL(triggered()), m_printPreviewWidget, SLOT(fitToWidth())); + toolBar->addAction(action); + action = new Action(Icon(QLatin1String("zoom-fit-best")), tr("Fit p&age"), this, + QLatin1String("printpreview_fit_page")); + connect(action, SIGNAL(triggered()), m_printPreviewWidget, SLOT(fitInView())); + toolBar->addAction(action); + m_zoomToAction = new ZoomAction(Icon(QLatin1String("zoom-original")), tr("&Zoom"), this, + QLatin1String("printpreview_zoom_to")); + connect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); + toolBar->addAction(m_zoomToAction); + toolBar->addAction(StandardAction::zoomIn(this, SLOT(zoomIn()), this)); + toolBar->addAction(StandardAction::zoomOut(this, SLOT(zoomOut()), this)); + action = new Action(Icon(QLatin1String("document-print")), tr("&Print"), this, + QLatin1String("printpreview_print")); + connect(action, SIGNAL(triggered()), this, SLOT(print())); + toolBar->addAction(action); + action = new Action(Icon(QLatin1String("window-close")), tr("&Close"), this, + QLatin1String("printpreview_close")); + connect(action, SIGNAL(triggered()), this, SLOT(reject())); + toolBar->addAction(action); - mainLayout->addWidget(toolBar); - mainLayout->addWidget(m_printPreviewWidget); - setLayout(mainLayout); + mainLayout->addWidget(toolBar); + mainLayout->addWidget(m_printPreviewWidget); + setLayout(mainLayout); - m_zoomToAction->setZoomFactor(1.0); + m_zoomToAction->setZoomFactor(1.0); } void PrintPreviewDialog::setVisible(bool visible) { - // this will make the dialog get a decent default size - if (visible && !m_initialized) - { - m_printPreviewWidget->updatePreview(); - m_initialized = true; - } - QDialog::setVisible(visible); + // this will make the dialog get a decent default size + if (visible && !m_initialized) { + m_printPreviewWidget->updatePreview(); + m_initialized = true; + } + QDialog::setVisible(visible); } void PrintPreviewDialog::setZoomFactor(qreal zoomFactor) { - m_printPreviewWidget->setZoomFactor(zoomFactor); + m_printPreviewWidget->setZoomFactor(zoomFactor); } void PrintPreviewDialog::updateZoomFactor() { - disconnect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); - m_zoomToAction->setZoomFactor(m_printPreviewWidget->zoomFactor()); - connect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); + disconnect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); + m_zoomToAction->setZoomFactor(m_printPreviewWidget->zoomFactor()); + connect(m_zoomToAction, SIGNAL(zoomFactorAdded(qreal)), this, SLOT(setZoomFactor(qreal))); } void PrintPreviewDialog::zoomIn() { - const qreal zoomFactor = m_printPreviewWidget->zoomFactor(); - m_zoomToAction->setZoomFactor(zoomFactor + (zoomFactor > 0.99 ? - (zoomFactor > 1.99 ? 0.5 : 0.2) : 0.1)); + const qreal zoomFactor = m_printPreviewWidget->zoomFactor(); + m_zoomToAction->setZoomFactor(zoomFactor + + (zoomFactor > 0.99 ? (zoomFactor > 1.99 ? 0.5 : 0.2) : 0.1)); } void PrintPreviewDialog::zoomOut() { - const qreal zoomFactor = m_printPreviewWidget->zoomFactor(); - m_zoomToAction->setZoomFactor(zoomFactor - (zoomFactor > 1.01 ? - (zoomFactor > 2.01 ? 0.5 : 0.2) : 0.1)); + const qreal zoomFactor = m_printPreviewWidget->zoomFactor(); + m_zoomToAction->setZoomFactor(zoomFactor + - (zoomFactor > 1.01 ? (zoomFactor > 2.01 ? 0.5 : 0.2) : 0.1)); } void PrintPreviewDialog::print() { - m_printPreviewWidget->print(); - accept(); + m_printPreviewWidget->print(); + accept(); } diff --git a/common/utils/printpreviewdialog.h b/common/utils/printpreviewdialog.h index 4a58f41..5d19fd8 100644 --- a/common/utils/printpreviewdialog.h +++ b/common/utils/printpreviewdialog.h @@ -28,26 +28,26 @@ class ZoomAction; class PrintPreviewDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit PrintPreviewDialog(QPrinter *printer, QWidget *parent = 0); + explicit PrintPreviewDialog(QPrinter *printer, QWidget *parent = 0); - void setVisible(bool visible); + void setVisible(bool visible); Q_SIGNALS: - void paintRequested(QPrinter *printer); + void paintRequested(QPrinter *printer); private Q_SLOTS: - void setZoomFactor(qreal zoomFactor); - void updateZoomFactor(); - void zoomIn(); - void zoomOut(); - void print(); + void setZoomFactor(qreal zoomFactor); + void updateZoomFactor(); + void zoomIn(); + void zoomOut(); + void print(); private: - QPrintPreviewWidget *m_printPreviewWidget; - ZoomAction *m_zoomToAction; - bool m_initialized; + QPrintPreviewWidget *m_printPreviewWidget; + ZoomAction *m_zoomToAction; + bool m_initialized; }; #endif diff --git a/common/utils/recentfilesaction.cpp b/common/utils/recentfilesaction.cpp index e25fc86..a7ebad9 100644 --- a/common/utils/recentfilesaction.cpp +++ b/common/utils/recentfilesaction.cpp @@ -23,162 +23,160 @@ #include "url.h" #ifdef KTIKZ_USE_KDE -#include -#include -#include +# include +# include +# include -RecentFilesAction::RecentFilesAction(QObject *parent) - : KRecentFilesAction(parent) +RecentFilesAction::RecentFilesAction(QObject *parent) : KRecentFilesAction(parent) { - Action::actionCollection()->addAction(QLatin1String("file_open_recent"), this); - //connect(this, SIGNAL(urlSelected(QUrl)), this, SLOT(selectUrl(QUrl))); + Action::actionCollection()->addAction(QLatin1String("file_open_recent"), this); + // connect(this, SIGNAL(urlSelected(QUrl)), this, SLOT(selectUrl(QUrl))); } RecentFilesAction::RecentFilesAction(const QString &text, QObject *parent) - : KRecentFilesAction(text, parent) + : KRecentFilesAction(text, parent) { - Action::actionCollection()->addAction(QLatin1String("file_open_recent"), this); - //connect(this, SIGNAL(urlSelected(QUrl)), this, SLOT(selectUrl(QUrl))); + Action::actionCollection()->addAction(QLatin1String("file_open_recent"), this); + // connect(this, SIGNAL(urlSelected(QUrl)), this, SLOT(selectUrl(QUrl))); } RecentFilesAction::RecentFilesAction(const Icon &icon, const QString &text, QObject *parent) - : KRecentFilesAction(icon, text, parent) + : KRecentFilesAction(icon, text, parent) { - Action::actionCollection()->addAction(QLatin1String("file_open_recent"), this); - //connect(this, SIGNAL(urlSelected(QUrl)), this, SLOT(selectUrl(QUrl))); + Action::actionCollection()->addAction(QLatin1String("file_open_recent"), this); + // connect(this, SIGNAL(urlSelected(QUrl)), this, SLOT(selectUrl(QUrl))); } void RecentFilesAction::loadEntries() { - KRecentFilesAction::loadEntries(KSharedConfig::openConfig()->group(QLatin1String("Recent Files"))); - setEnabled(true); + KRecentFilesAction::loadEntries( + KSharedConfig::openConfig()->group(QLatin1String("Recent Files"))); + setEnabled(true); } void RecentFilesAction::saveEntries() { - KRecentFilesAction::saveEntries(KSharedConfig::openConfig()->group(QLatin1String("Recent Files"))); - KSharedConfig::openConfig()->sync(); + KRecentFilesAction::saveEntries( + KSharedConfig::openConfig()->group(QLatin1String("Recent Files"))); + KSharedConfig::openConfig()->sync(); } #else -#include -#include +# include +# include -RecentFilesAction::RecentFilesAction(QObject *parent) - : Action(parent) +RecentFilesAction::RecentFilesAction(QObject *parent) : Action(parent) { - createMenu(); + createMenu(); } -RecentFilesAction::RecentFilesAction(const QString &text, QObject *parent) - : Action(text, parent) +RecentFilesAction::RecentFilesAction(const QString &text, QObject *parent) : Action(text, parent) { - createMenu(); + createMenu(); } RecentFilesAction::RecentFilesAction(const Icon &icon, const QString &text, QObject *parent) - : Action(icon, text, parent) + : Action(icon, text, parent) { - createMenu(); + createMenu(); } RecentFilesAction::~RecentFilesAction() { - delete m_recentMenu; + delete m_recentMenu; } void RecentFilesAction::createMenu() { - m_numOfRecentFiles = 5; // is set correctly in loadEntries() which must be executed before anything else happens with the menu + m_numOfRecentFiles = 5; // is set correctly in loadEntries() which must be executed before + // anything else happens with the menu - setObjectName(QLatin1String("file_open_recent")); - setText(tr("Open &Recent")); - setIcon(Icon(QLatin1String("document-open-recent"))); + setObjectName(QLatin1String("file_open_recent")); + setText(tr("Open &Recent")); + setIcon(Icon(QLatin1String("document-open-recent"))); - m_recentMenu = new QMenu(); - setMenu(m_recentMenu); + m_recentMenu = new QMenu(); + setMenu(m_recentMenu); } void RecentFilesAction::openRecentFile() { - QAction *action = qobject_cast(sender()); - if (action) -#ifdef Q_OS_WIN32 - Q_EMIT urlSelected(Url(action->data().toString())); -#else - Q_EMIT urlSelected(Url(QLatin1String("file://") + action->data().toString())); -#endif + QAction *action = qobject_cast(sender()); + if (action) +# ifdef Q_OS_WIN32 + Q_EMIT urlSelected(Url(action->data().toString())); +# else + Q_EMIT urlSelected(Url(QLatin1String("file://") + action->data().toString())); +# endif } void RecentFilesAction::createRecentFilesList() { - m_recentFileActions.clear(); - for (int i = 0; i < m_numOfRecentFiles; ++i) - { - QAction *action = new QAction(this); - action->setVisible(false); - connect(action, SIGNAL(triggered()), this, SLOT(openRecentFile())); - m_recentFileActions.append(action); - } + m_recentFileActions.clear(); + for (int i = 0; i < m_numOfRecentFiles; ++i) { + QAction *action = new QAction(this); + action->setVisible(false); + connect(action, SIGNAL(triggered()), this, SLOT(openRecentFile())); + m_recentFileActions.append(action); + } - // when the user has decreased the maximum number of recent files, then we must remove the superfluous entries - while (m_recentFilesList.size() > m_numOfRecentFiles) - m_recentFilesList.removeLast(); + // when the user has decreased the maximum number of recent files, then we must remove the + // superfluous entries + while (m_recentFilesList.size() > m_numOfRecentFiles) + m_recentFilesList.removeLast(); - updateRecentFilesList(); + updateRecentFilesList(); - m_recentMenu->clear(); // this also deletes all the QActions in the menu - m_recentMenu->addActions(m_recentFileActions); + m_recentMenu->clear(); // this also deletes all the QActions in the menu + m_recentMenu->addActions(m_recentFileActions); } void RecentFilesAction::loadEntries() { - QSettings settings; - m_numOfRecentFiles = settings.value(QLatin1String("RecentFilesNumber"), 5).toInt(); + QSettings settings; + m_numOfRecentFiles = settings.value(QLatin1String("RecentFilesNumber"), 5).toInt(); - m_recentFilesList = settings.value(QLatin1String("RecentFiles")).toStringList(); - setEnabled(true); + m_recentFilesList = settings.value(QLatin1String("RecentFiles")).toStringList(); + setEnabled(true); } void RecentFilesAction::saveEntries() { - QSettings settings; - if (m_recentFilesList.size() > 0) - settings.setValue(QLatin1String("RecentFiles"), m_recentFilesList); + QSettings settings; + if (m_recentFilesList.size() > 0) + settings.setValue(QLatin1String("RecentFiles"), m_recentFilesList); } void RecentFilesAction::updateRecentFilesList() { - m_recentMenu->setEnabled(m_recentFilesList.count() > 0); + m_recentMenu->setEnabled(m_recentFilesList.count() > 0); - for (int i = 0; i < m_recentFilesList.count(); ++i) - { - m_recentFileActions[i]->setText(m_recentFilesList.at(i)); - m_recentFileActions[i]->setData(m_recentFilesList.at(i)); - m_recentFileActions[i]->setVisible(true); - } - for (int i = m_recentFilesList.count(); i < m_numOfRecentFiles; ++i) - m_recentFileActions[i]->setVisible(false); + for (int i = 0; i < m_recentFilesList.count(); ++i) { + m_recentFileActions[i]->setText(m_recentFilesList.at(i)); + m_recentFileActions[i]->setData(m_recentFilesList.at(i)); + m_recentFileActions[i]->setVisible(true); + } + for (int i = m_recentFilesList.count(); i < m_numOfRecentFiles; ++i) + m_recentFileActions[i]->setVisible(false); } void RecentFilesAction::addUrl(const QUrl &url, const QString &name) { - Q_UNUSED(name); - const QString fileName = url.path(); + Q_UNUSED(name); + const QString fileName = url.path(); - if (m_recentFilesList.contains(fileName)) - m_recentFilesList.move(m_recentFilesList.indexOf(fileName), 0); - else - { - if (m_recentFilesList.count() >= m_numOfRecentFiles) - m_recentFilesList.removeLast(); - m_recentFilesList.prepend(fileName); - } - updateRecentFilesList(); + if (m_recentFilesList.contains(fileName)) + m_recentFilesList.move(m_recentFilesList.indexOf(fileName), 0); + else { + if (m_recentFilesList.count() >= m_numOfRecentFiles) + m_recentFilesList.removeLast(); + m_recentFilesList.prepend(fileName); + } + updateRecentFilesList(); } void RecentFilesAction::removeUrl(const QUrl &url) { - m_recentFilesList.removeAll(url.path()); - updateRecentFilesList(); + m_recentFilesList.removeAll(url.path()); + updateRecentFilesList(); } #endif diff --git a/common/utils/recentfilesaction.h b/common/utils/recentfilesaction.h index 20a5f27..0694ea9 100644 --- a/common/utils/recentfilesaction.h +++ b/common/utils/recentfilesaction.h @@ -23,56 +23,56 @@ class Icon; class Url; #ifdef KTIKZ_USE_KDE -#include +# include class KActionCollection; class RecentFilesAction : public KRecentFilesAction { - Q_OBJECT + Q_OBJECT public: - explicit RecentFilesAction(QObject *parent); - RecentFilesAction(const QString &text, QObject *parent); - RecentFilesAction(const Icon &icon, const QString &text, QObject *parent); + explicit RecentFilesAction(QObject *parent); + RecentFilesAction(const QString &text, QObject *parent); + RecentFilesAction(const Icon &icon, const QString &text, QObject *parent); - void createRecentFilesList() {} - void loadEntries(); - void saveEntries(); + void createRecentFilesList() { } + void loadEntries(); + void saveEntries(); }; #else -#include "action.h" +# include "action.h" class RecentFilesAction : public Action { - Q_OBJECT + Q_OBJECT public: - explicit RecentFilesAction(QObject *parent); - RecentFilesAction(const QString &text, QObject *parent); - RecentFilesAction(const Icon &icon, const QString &text, QObject *parent); - ~RecentFilesAction(); + explicit RecentFilesAction(QObject *parent); + RecentFilesAction(const QString &text, QObject *parent); + RecentFilesAction(const Icon &icon, const QString &text, QObject *parent); + ~RecentFilesAction(); - void createRecentFilesList(); - void loadEntries(); - void saveEntries(); - void addUrl(const QUrl &url, const QString &name = QString()); - void removeUrl(const QUrl &url); + void createRecentFilesList(); + void loadEntries(); + void saveEntries(); + void addUrl(const QUrl &url, const QString &name = QString()); + void removeUrl(const QUrl &url); Q_SIGNALS: - void urlSelected(const Url &url); + void urlSelected(const Url &url); private Q_SLOTS: - void openRecentFile(); + void openRecentFile(); private: - void createMenu(); - void updateRecentFilesList(); + void createMenu(); + void updateRecentFilesList(); - QMenu *m_recentMenu; - QList m_recentFileActions; - QStringList m_recentFilesList; - int m_numOfRecentFiles; + QMenu *m_recentMenu; + QList m_recentFileActions; + QStringList m_recentFilesList; + int m_numOfRecentFiles; }; #endif diff --git a/common/utils/selectaction.cpp b/common/utils/selectaction.cpp index 5113cf7..6d8208e 100644 --- a/common/utils/selectaction.cpp +++ b/common/utils/selectaction.cpp @@ -22,105 +22,105 @@ #include "icon.h" #ifdef KTIKZ_USE_KDE -#include +# include -SelectAction::SelectAction(QObject *parent, const QString &name) - : KSelectAction(parent) +SelectAction::SelectAction(QObject *parent, const QString &name) : KSelectAction(parent) { - if (!name.isEmpty()) - Action::actionCollection()->addAction(name, this); + if (!name.isEmpty()) + Action::actionCollection()->addAction(name, this); } SelectAction::SelectAction(const QString &text, QObject *parent, const QString &name) - : KSelectAction(text, parent) + : KSelectAction(text, parent) { - if (!name.isEmpty()) - Action::actionCollection()->addAction(name, this); + if (!name.isEmpty()) + Action::actionCollection()->addAction(name, this); } -SelectAction::SelectAction(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : KSelectAction(icon, text, parent) +SelectAction::SelectAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name) + : KSelectAction(icon, text, parent) { - if (!name.isEmpty()) - Action::actionCollection()->addAction(name, this); + if (!name.isEmpty()) + Action::actionCollection()->addAction(name, this); } #else -#include -#include -#include +# include +# include +# include -SelectAction::SelectAction(QObject *parent, const QString &name) - : QWidgetAction(parent) +SelectAction::SelectAction(QObject *parent, const QString &name) : QWidgetAction(parent) { - init(name); + init(name); } SelectAction::SelectAction(const QString &text, QObject *parent, const QString &name) - : QWidgetAction(parent) + : QWidgetAction(parent) { - init(name); - setText(text); + init(name); + setText(text); } -SelectAction::SelectAction(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : QWidgetAction(parent) +SelectAction::SelectAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name) + : QWidgetAction(parent) { - init(name); - setIcon(icon); - setText(text); + init(name); + setIcon(icon); + setText(text); } void SelectAction::init(const QString &name) { - if (!name.isEmpty()) - setObjectName(name); + if (!name.isEmpty()) + setObjectName(name); - m_selectCombo = new QComboBox; - setDefaultWidget(m_selectCombo); - connect(m_selectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setCurrentItem())); + m_selectCombo = new QComboBox; + setDefaultWidget(m_selectCombo); + connect(m_selectCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setCurrentItem())); } SelectAction::~SelectAction() { - delete m_selectCombo; + delete m_selectCombo; } void SelectAction::setEditable(bool editable) { - m_selectCombo->setEditable(editable); - if (editable) - connect(m_selectCombo->lineEdit(), SIGNAL(returnPressed()), this, SLOT(setCurrentItem())); + m_selectCombo->setEditable(editable); + if (editable) + connect(m_selectCombo->lineEdit(), SIGNAL(returnPressed()), this, SLOT(setCurrentItem())); } void SelectAction::setCurrentItem() { - const QString text = m_selectCombo->currentText(); - Q_EMIT triggered(text); + const QString text = m_selectCombo->currentText(); + Q_EMIT triggered(text); } void SelectAction::removeAllActions() { - m_selectCombo->clear(); + m_selectCombo->clear(); } void SelectAction::setItems(const QStringList &items) { - m_selectCombo->clear(); - m_selectCombo->addItems(items); + m_selectCombo->clear(); + m_selectCombo->addItems(items); } void SelectAction::setCurrentItem(int index) { - m_selectCombo->setCurrentIndex(index); - if (m_selectCombo->isEditable()) - m_selectCombo->lineEdit()->setText(m_selectCombo->currentText()); + m_selectCombo->setCurrentIndex(index); + if (m_selectCombo->isEditable()) + m_selectCombo->lineEdit()->setText(m_selectCombo->currentText()); } QStringList SelectAction::items() const { - QStringList itemList; - for (int i = 0; i < m_selectCombo->count(); ++i) - itemList << m_selectCombo->itemText(i); - return itemList; + QStringList itemList; + for (int i = 0; i < m_selectCombo->count(); ++i) + itemList << m_selectCombo->itemText(i); + return itemList; } #endif diff --git a/common/utils/selectaction.h b/common/utils/selectaction.h index 0ebc980..31d913e 100644 --- a/common/utils/selectaction.h +++ b/common/utils/selectaction.h @@ -22,49 +22,51 @@ class Icon; #ifdef KTIKZ_USE_KDE -#include +# include class SelectAction : public KSelectAction { - Q_OBJECT + Q_OBJECT public: - explicit SelectAction(QObject *parent, const QString &name = QString()); - SelectAction(const QString &text, QObject *parent, const QString &name = QString()); - SelectAction(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); + explicit SelectAction(QObject *parent, const QString &name = QString()); + SelectAction(const QString &text, QObject *parent, const QString &name = QString()); + SelectAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name = QString()); }; #else -#include -#include +# include +# include class QComboBox; class SelectAction : public QWidgetAction { - Q_OBJECT + Q_OBJECT public: - explicit SelectAction(QObject *parent, const QString &name = QString()); - SelectAction(const QString &text, QObject *parent, const QString &name = QString()); - SelectAction(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); - ~SelectAction(); + explicit SelectAction(QObject *parent, const QString &name = QString()); + SelectAction(const QString &text, QObject *parent, const QString &name = QString()); + SelectAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name = QString()); + ~SelectAction(); - void setEditable(bool editable); - void removeAllActions(); - void setItems(const QStringList &items); - void setCurrentItem(int index); - QStringList items() const; + void setEditable(bool editable); + void removeAllActions(); + void setItems(const QStringList &items); + void setCurrentItem(int index); + QStringList items() const; Q_SIGNALS: - void triggered(const QString &text); + void triggered(const QString &text); private Q_SLOTS: - void setCurrentItem(); + void setCurrentItem(); private: - void init(const QString &name); + void init(const QString &name); - QComboBox *m_selectCombo; + QComboBox *m_selectCombo; }; #endif diff --git a/common/utils/standardaction.cpp b/common/utils/standardaction.cpp index 1200219..e78cba8 100644 --- a/common/utils/standardaction.cpp +++ b/common/utils/standardaction.cpp @@ -19,374 +19,377 @@ #include "standardaction.h" #ifdef KTIKZ_USE_KDE -#include -#include -#include +# include +# include +# include #else -#include +# include #endif #include "icon.h" #include "action.h" #include "recentfilesaction.h" -namespace StandardAction -{ +namespace StandardAction { #ifdef KTIKZ_USE_KDE // XXX the following is an ugly hack, but I don't know how to promote a QAction to an Action static Action *copyAction(QAction *action, const QObject *recvr, const char *slot) { - Action *newAction = new Action(Icon(action->icon()), action->text(), action->parent()); - newAction->setShortcut(action->shortcut()); - newAction->setData(action->data()); - newAction->setObjectName(action->objectName()); - QObject::connect(newAction, SIGNAL(triggered()), recvr, slot); - Action::actionCollection()->addAction(newAction->objectName(), newAction); - return newAction; + Action *newAction = new Action(Icon(action->icon()), action->text(), action->parent()); + newAction->setShortcut(action->shortcut()); + newAction->setData(action->data()); + newAction->setObjectName(action->objectName()); + QObject::connect(newAction, SIGNAL(triggered()), recvr, slot); + Action::actionCollection()->addAction(newAction->objectName(), newAction); + return newAction; } Action *openNew(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::openNew(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::openNew(recvr, slot, parent), recvr, slot); } /* QAction *openNew(const QObject *recvr, const char *slot, QObject *parent) { - QAction *action = KStandardAction::openNew(recvr, slot, parent); - Action::actionCollection()->addAction(action->objectName(), action); - return action; + QAction *action = KStandardAction::openNew(recvr, slot, parent); + Action::actionCollection()->addAction(action->objectName(), action); + return action; } */ Action *open(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::open(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::open(recvr, slot, parent), recvr, slot); } RecentFilesAction *openRecent(const QObject *recvr, const char *slot, QObject *parent) { - KRecentFilesAction *action = KStandardAction::openRecent(recvr, slot, parent); - RecentFilesAction *newAction = new RecentFilesAction(Icon(action->icon()), action->text(), action->parent()); - newAction->setShortcut(action->shortcut()); - newAction->setData(action->data()); - newAction->setObjectName(action->objectName()); - newAction->setToolBarMode(KRecentFilesAction::MenuMode); - newAction->setToolButtonPopupMode(QToolButton::MenuButtonPopup); - QObject::connect(newAction, SIGNAL(urlSelected(QUrl)), recvr, slot); - Action::actionCollection()->addAction(newAction->objectName(), newAction); - return newAction; + KRecentFilesAction *action = KStandardAction::openRecent(recvr, slot, parent); + RecentFilesAction *newAction = + new RecentFilesAction(Icon(action->icon()), action->text(), action->parent()); + newAction->setShortcut(action->shortcut()); + newAction->setData(action->data()); + newAction->setObjectName(action->objectName()); + newAction->setToolBarMode(KRecentFilesAction::MenuMode); + newAction->setToolButtonPopupMode(QToolButton::MenuButtonPopup); + QObject::connect(newAction, SIGNAL(urlSelected(QUrl)), recvr, slot); + Action::actionCollection()->addAction(newAction->objectName(), newAction); + return newAction; } /* KRecentFilesAction *openRecent(const QObject *recvr, const char *slot, QObject *parent) { - KRecentFilesAction *action = KStandardAction::openRecent(recvr, slot, parent); - action->setToolBarMode(KRecentFilesAction::MenuMode); - action->setToolButtonPopupMode(QToolButton::MenuButtonPopup); - Action::actionCollection()->addAction(action->objectName(), action); - return action; + KRecentFilesAction *action = KStandardAction::openRecent(recvr, slot, parent); + action->setToolBarMode(KRecentFilesAction::MenuMode); + action->setToolButtonPopupMode(QToolButton::MenuButtonPopup); + Action::actionCollection()->addAction(action->objectName(), action); + return action; } */ Action *save(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::save(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::save(recvr, slot, parent), recvr, slot); } Action *saveAs(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::saveAs(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::saveAs(recvr, slot, parent), recvr, slot); } Action *close(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::close(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::close(recvr, slot, parent), recvr, slot); } Action *quit(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::quit(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::quit(recvr, slot, parent), recvr, slot); } Action *undo(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::undo(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::undo(recvr, slot, parent), recvr, slot); } Action *redo(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::redo(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::redo(recvr, slot, parent), recvr, slot); } Action *cut(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::cut(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::cut(recvr, slot, parent), recvr, slot); } Action *copy(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::copy(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::copy(recvr, slot, parent), recvr, slot); } Action *paste(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::paste(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::paste(recvr, slot, parent), recvr, slot); } Action *selectAll(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::selectAll(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::selectAll(recvr, slot, parent), recvr, slot); } Action *find(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::find(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::find(recvr, slot, parent), recvr, slot); } Action *findNext(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::findNext(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::findNext(recvr, slot, parent), recvr, slot); } Action *findPrev(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::findPrev(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::findPrev(recvr, slot, parent), recvr, slot); } Action *replace(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::replace(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::replace(recvr, slot, parent), recvr, slot); } Action *gotoLine(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::gotoLine(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::gotoLine(recvr, slot, parent), recvr, slot); } Action *zoomIn(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::zoomIn(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::zoomIn(recvr, slot, parent), recvr, slot); } Action *zoomOut(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::zoomOut(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::zoomOut(recvr, slot, parent), recvr, slot); } Action *preferences(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::preferences(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::preferences(recvr, slot, parent), recvr, slot); } Action *printPreview(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::printPreview(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::printPreview(recvr, slot, parent), recvr, slot); } Action *print(const QObject *recvr, const char *slot, QObject *parent) { - return copyAction(KStandardAction::print(recvr, slot, parent), recvr, slot); + return copyAction(KStandardAction::print(recvr, slot, parent), recvr, slot); } #else static Action *createAction(int which, const QObject *recvr, const char *slot, QObject *parent) { - QString iconName; - QString text; - QKeySequence::StandardKey key = QKeySequence::UnknownKey; + QString iconName; + QString text; + QKeySequence::StandardKey key = QKeySequence::UnknownKey; - switch (which) - { - case 0: - iconName = QLatin1String("document-new"); - text = QCoreApplication::translate("StandardAction", "&New"); - key = QKeySequence::New; - break; - case 1: - iconName = QLatin1String("document-open"); - text = QCoreApplication::translate("StandardAction", "&Open..."); - key = QKeySequence::Open; - break; - case 2: - iconName = QLatin1String("document-save"); - text = QCoreApplication::translate("StandardAction", "&Save"); - key = QKeySequence::Save; - break; - case 3: - iconName = QLatin1String("document-save-as"); - text = QCoreApplication::translate("StandardAction", "Save &As..."); - break; - case 4: - iconName = QLatin1String("window-close"); - text = QCoreApplication::translate("StandardAction", "&Close"); - key = QKeySequence::Close; - break; - case 5: - iconName = QLatin1String("application-exit"); - text = QCoreApplication::translate("StandardAction", "&Quit"); - break; - case 6: - iconName = QLatin1String("edit-undo"); - text = QCoreApplication::translate("StandardAction", "&Undo"); - key = QKeySequence::Undo; - break; - case 7: - iconName = QLatin1String("edit-redo"); - text = QCoreApplication::translate("StandardAction", "Re&do"); - key = QKeySequence::Redo; - break; - case 8: - iconName = QLatin1String("edit-cut"); - text = QCoreApplication::translate("StandardAction", "Cu&t"); - key = QKeySequence::Cut; - break; - case 9: - iconName = QLatin1String("edit-copy"); - text = QCoreApplication::translate("StandardAction", "&Copy"); - key = QKeySequence::Copy; - break; - case 10: - iconName = QLatin1String("edit-paste"); - text = QCoreApplication::translate("StandardAction", "&Paste"); - key = QKeySequence::Paste; - break; - case 11: - text = QCoreApplication::translate("StandardAction", "Select &All"); - key = QKeySequence::SelectAll; - break; - case 12: - iconName = QLatin1String("edit-find"); - text = QCoreApplication::translate("StandardAction", "&Find..."); - key = QKeySequence::Find; - break; - case 13: - iconName = QLatin1String("go-down"); - text = QCoreApplication::translate("StandardAction", "Find &Next"); - key = QKeySequence::FindNext; - break; - case 14: - iconName = QLatin1String("go-up"); - text = QCoreApplication::translate("StandardAction", "Find Pre&vious"); - key = QKeySequence::FindPrevious; - break; - case 15: - iconName = QLatin1String("edit-find-replace"); - text = QCoreApplication::translate("StandardAction", "&Replace..."); - key = QKeySequence::Replace; - break; - case 16: - iconName = QLatin1String("go-jump"); - text = QCoreApplication::translate("StandardAction", "&Go to Line..."); - break; - case 17: - iconName = QLatin1String("zoom-in"); - text = QCoreApplication::translate("StandardAction", "Zoom &In"); - key = QKeySequence::ZoomIn; - break; - case 18: - iconName = QLatin1String("zoom-out"); - text = QCoreApplication::translate("StandardAction", "Zoom &Out"); - key = QKeySequence::ZoomOut; - break; - case 19: - iconName = QLatin1String("configure"); - text = QCoreApplication::translate("StandardAction", "&Configure %1...").arg(QCoreApplication::applicationName()); - break; - case 20: - iconName = QLatin1String("document-print-preview"); - text = QCoreApplication::translate("StandardAction", "Print Pre&view..."); - break; - case 21: - iconName = QLatin1String("document-print"); - text = QCoreApplication::translate("StandardAction", "&Print..."); - key = QKeySequence::Print; - break; - } + switch (which) { + case 0: + iconName = QLatin1String("document-new"); + text = QCoreApplication::translate("StandardAction", "&New"); + key = QKeySequence::New; + break; + case 1: + iconName = QLatin1String("document-open"); + text = QCoreApplication::translate("StandardAction", "&Open..."); + key = QKeySequence::Open; + break; + case 2: + iconName = QLatin1String("document-save"); + text = QCoreApplication::translate("StandardAction", "&Save"); + key = QKeySequence::Save; + break; + case 3: + iconName = QLatin1String("document-save-as"); + text = QCoreApplication::translate("StandardAction", "Save &As..."); + break; + case 4: + iconName = QLatin1String("window-close"); + text = QCoreApplication::translate("StandardAction", "&Close"); + key = QKeySequence::Close; + break; + case 5: + iconName = QLatin1String("application-exit"); + text = QCoreApplication::translate("StandardAction", "&Quit"); + break; + case 6: + iconName = QLatin1String("edit-undo"); + text = QCoreApplication::translate("StandardAction", "&Undo"); + key = QKeySequence::Undo; + break; + case 7: + iconName = QLatin1String("edit-redo"); + text = QCoreApplication::translate("StandardAction", "Re&do"); + key = QKeySequence::Redo; + break; + case 8: + iconName = QLatin1String("edit-cut"); + text = QCoreApplication::translate("StandardAction", "Cu&t"); + key = QKeySequence::Cut; + break; + case 9: + iconName = QLatin1String("edit-copy"); + text = QCoreApplication::translate("StandardAction", "&Copy"); + key = QKeySequence::Copy; + break; + case 10: + iconName = QLatin1String("edit-paste"); + text = QCoreApplication::translate("StandardAction", "&Paste"); + key = QKeySequence::Paste; + break; + case 11: + text = QCoreApplication::translate("StandardAction", "Select &All"); + key = QKeySequence::SelectAll; + break; + case 12: + iconName = QLatin1String("edit-find"); + text = QCoreApplication::translate("StandardAction", "&Find..."); + key = QKeySequence::Find; + break; + case 13: + iconName = QLatin1String("go-down"); + text = QCoreApplication::translate("StandardAction", "Find &Next"); + key = QKeySequence::FindNext; + break; + case 14: + iconName = QLatin1String("go-up"); + text = QCoreApplication::translate("StandardAction", "Find Pre&vious"); + key = QKeySequence::FindPrevious; + break; + case 15: + iconName = QLatin1String("edit-find-replace"); + text = QCoreApplication::translate("StandardAction", "&Replace..."); + key = QKeySequence::Replace; + break; + case 16: + iconName = QLatin1String("go-jump"); + text = QCoreApplication::translate("StandardAction", "&Go to Line..."); + break; + case 17: + iconName = QLatin1String("zoom-in"); + text = QCoreApplication::translate("StandardAction", "Zoom &In"); + key = QKeySequence::ZoomIn; + break; + case 18: + iconName = QLatin1String("zoom-out"); + text = QCoreApplication::translate("StandardAction", "Zoom &Out"); + key = QKeySequence::ZoomOut; + break; + case 19: + iconName = QLatin1String("configure"); + text = QCoreApplication::translate("StandardAction", "&Configure %1...") + .arg(QCoreApplication::applicationName()); + break; + case 20: + iconName = QLatin1String("document-print-preview"); + text = QCoreApplication::translate("StandardAction", "Print Pre&view..."); + break; + case 21: + iconName = QLatin1String("document-print"); + text = QCoreApplication::translate("StandardAction", "&Print..."); + key = QKeySequence::Print; + break; + } - Action *action; - if (!iconName.isEmpty()) - action = new Action(Icon(iconName), text, parent); - else - action = new Action(text, parent); + Action *action; + if (!iconName.isEmpty()) + action = new Action(Icon(iconName), text, parent); + else + action = new Action(text, parent); - if (which == 5) - action->setShortcut(QCoreApplication::translate("StandardAction", "Ctrl+Q", "File|Quit")); - else if (which == 16) - action->setShortcut(QCoreApplication::translate("StandardAction", "Ctrl+G", "Edit|Go to Line")); - else if (which != 3 && which != 19) - action->setShortcut(key); - QObject::connect(action, SIGNAL(triggered()), recvr, slot); - return action; + if (which == 5) + action->setShortcut(QCoreApplication::translate("StandardAction", "Ctrl+Q", "File|Quit")); + else if (which == 16) + action->setShortcut( + QCoreApplication::translate("StandardAction", "Ctrl+G", "Edit|Go to Line")); + else if (which != 3 && which != 19) + action->setShortcut(key); + QObject::connect(action, SIGNAL(triggered()), recvr, slot); + return action; } Action *openNew(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(0, recvr, slot, parent); + return createAction(0, recvr, slot, parent); } Action *open(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(1, recvr, slot, parent); + return createAction(1, recvr, slot, parent); } RecentFilesAction *openRecent(const QObject *recvr, const char *slot, QObject *parent) { - RecentFilesAction *action = new RecentFilesAction(Icon(QLatin1String("document-open-recent")), QCoreApplication::translate("StandardAction", "&Open Recent"), parent); - QObject::connect(action, SIGNAL(urlSelected(Url)), recvr, slot); - return action; + RecentFilesAction *action = new RecentFilesAction( + Icon(QLatin1String("document-open-recent")), + QCoreApplication::translate("StandardAction", "&Open Recent"), parent); + QObject::connect(action, SIGNAL(urlSelected(Url)), recvr, slot); + return action; } Action *save(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(2, recvr, slot, parent); + return createAction(2, recvr, slot, parent); } Action *saveAs(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(3, recvr, slot, parent); + return createAction(3, recvr, slot, parent); } Action *close(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(4, recvr, slot, parent); + return createAction(4, recvr, slot, parent); } Action *quit(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(5, recvr, slot, parent); + return createAction(5, recvr, slot, parent); } Action *undo(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(6, recvr, slot, parent); + return createAction(6, recvr, slot, parent); } Action *redo(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(7, recvr, slot, parent); + return createAction(7, recvr, slot, parent); } Action *cut(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(8, recvr, slot, parent); + return createAction(8, recvr, slot, parent); } Action *copy(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(9, recvr, slot, parent); + return createAction(9, recvr, slot, parent); } Action *paste(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(10, recvr, slot, parent); + return createAction(10, recvr, slot, parent); } Action *selectAll(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(11, recvr, slot, parent); + return createAction(11, recvr, slot, parent); } Action *find(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(12, recvr, slot, parent); + return createAction(12, recvr, slot, parent); } Action *findNext(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(13, recvr, slot, parent); + return createAction(13, recvr, slot, parent); } Action *findPrev(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(14, recvr, slot, parent); + return createAction(14, recvr, slot, parent); } Action *replace(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(15, recvr, slot, parent); + return createAction(15, recvr, slot, parent); } Action *gotoLine(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(16, recvr, slot, parent); + return createAction(16, recvr, slot, parent); } Action *zoomIn(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(17, recvr, slot, parent); + return createAction(17, recvr, slot, parent); } Action *zoomOut(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(18, recvr, slot, parent); + return createAction(18, recvr, slot, parent); } Action *preferences(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(19, recvr, slot, parent); + return createAction(19, recvr, slot, parent); } Action *printPreview(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(20, recvr, slot, parent); + return createAction(20, recvr, slot, parent); } Action *print(const QObject *recvr, const char *slot, QObject *parent) { - return createAction(21, recvr, slot, parent); + return createAction(21, recvr, slot, parent); } #endif -} +} // namespace StandardAction diff --git a/common/utils/standardaction.h b/common/utils/standardaction.h index 02bc8dc..ba052c8 100644 --- a/common/utils/standardaction.h +++ b/common/utils/standardaction.h @@ -23,8 +23,7 @@ class Action; class RecentFilesAction; class QObject; -namespace StandardAction -{ +namespace StandardAction { Action *openNew(const QObject *recvr, const char *slot, QObject *parent); Action *open(const QObject *recvr, const char *slot, QObject *parent); RecentFilesAction *openRecent(const QObject *recvr, const char *slot, QObject *parent); @@ -48,6 +47,6 @@ Action *zoomOut(const QObject *recvr, const char *slot, QObject *parent); Action *preferences(const QObject *recvr, const char *slot, QObject *parent); Action *printPreview(const QObject *recvr, const char *slot, QObject *parent); Action *print(const QObject *recvr, const char *slot, QObject *parent); -} +} // namespace StandardAction #endif diff --git a/common/utils/tempdir.cpp b/common/utils/tempdir.cpp index b7fc9ff..d20769c 100644 --- a/common/utils/tempdir.cpp +++ b/common/utils/tempdir.cpp @@ -20,22 +20,20 @@ #include - // #include #include -TempDir::TempDir(const QString &directoryPrefix) - : QTemporaryDir(directoryPrefix) +TempDir::TempDir(const QString &directoryPrefix) : QTemporaryDir(directoryPrefix) { - setAutoRemove(true); + setAutoRemove(true); } const QString TempDir::location() const { -// const QString tempDirBase = KStandardDirs::locateLocal("tmp", KGlobal::mainComponent().componentName()); -// const int end = tempDirBase.lastIndexOf(QLatin1Char('/')); -// return tempDirBase.mid(0, end); - return QTemporaryDir::path(); + // const QString tempDirBase = KStandardDirs::locateLocal("tmp", + // KGlobal::mainComponent().componentName()); const int end = + // tempDirBase.lastIndexOf(QLatin1Char('/')); return tempDirBase.mid(0, end); + return QTemporaryDir::path(); } /*! @@ -44,17 +42,19 @@ const QString TempDir::location() const bool TempDir::cleanUp() { - const QString dirName = path(); - if (dirName.isEmpty()) // we must return in this case, otherwise in the QDir constructor below, the program's working directory is used and we really don't want to remove the files in that - return false; - - QDir tempDir(dirName); - if (!tempDir.exists()) - return false; - - bool success = true; - const QStringList fileList = tempDir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries); - Q_FOREACH (const QString &fileName, fileList) - success = success && tempDir.remove(fileName); - return success; + const QString dirName = path(); + if (dirName.isEmpty()) // we must return in this case, otherwise in the QDir constructor below, + // the program's working directory is used and we really don't want to + // remove the files in that + return false; + + QDir tempDir(dirName); + if (!tempDir.exists()) + return false; + + bool success = true; + const QStringList fileList = tempDir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries); + Q_FOREACH (const QString &fileName, fileList) + success = success && tempDir.remove(fileName); + return success; } diff --git a/common/utils/tempdir.h b/common/utils/tempdir.h index dc148a9..a56156e 100644 --- a/common/utils/tempdir.h +++ b/common/utils/tempdir.h @@ -24,10 +24,10 @@ class TempDir : public QTemporaryDir { public: - explicit TempDir(const QString &directoryPrefix = QString()); + explicit TempDir(const QString &directoryPrefix = QString()); - const QString location() const; - bool cleanUp(); + const QString location() const; + bool cleanUp(); }; #endif diff --git a/common/utils/toggleaction.cpp b/common/utils/toggleaction.cpp index d334fc0..e3539d5 100644 --- a/common/utils/toggleaction.cpp +++ b/common/utils/toggleaction.cpp @@ -22,52 +22,52 @@ #include "icon.h" #ifdef KTIKZ_USE_KDE -#include +# include -ToggleAction::ToggleAction(QObject *parent, const QString &name) - : KToggleAction(parent) +ToggleAction::ToggleAction(QObject *parent, const QString &name) : KToggleAction(parent) { - if (!name.isEmpty()) - Action::actionCollection()->addAction(name, this); + if (!name.isEmpty()) + Action::actionCollection()->addAction(name, this); } ToggleAction::ToggleAction(const QString &text, QObject *parent, const QString &name) - : KToggleAction(text, parent) + : KToggleAction(text, parent) { - if (!name.isEmpty()) - Action::actionCollection()->addAction(name, this); + if (!name.isEmpty()) + Action::actionCollection()->addAction(name, this); } -ToggleAction::ToggleAction(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : KToggleAction(icon, text, parent) +ToggleAction::ToggleAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name) + : KToggleAction(icon, text, parent) { - if (!name.isEmpty()) - Action::actionCollection()->addAction(name, this); + if (!name.isEmpty()) + Action::actionCollection()->addAction(name, this); } #else -ToggleAction::ToggleAction(QObject *parent, const QString &name) - : QAction(parent) +ToggleAction::ToggleAction(QObject *parent, const QString &name) : QAction(parent) { - init(name); + init(name); } ToggleAction::ToggleAction(const QString &text, QObject *parent, const QString &name) - : QAction(text, parent) + : QAction(text, parent) { - init(name); + init(name); } -ToggleAction::ToggleAction(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : QAction(icon, text, parent) +ToggleAction::ToggleAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name) + : QAction(icon, text, parent) { - init(name); + init(name); } void ToggleAction::init(const QString &name) { - if (!name.isEmpty()) - setObjectName(name); + if (!name.isEmpty()) + setObjectName(name); - setCheckable(true); + setCheckable(true); } #endif diff --git a/common/utils/toggleaction.h b/common/utils/toggleaction.h index 2ee1361..a4efa49 100644 --- a/common/utils/toggleaction.h +++ b/common/utils/toggleaction.h @@ -22,32 +22,34 @@ class Icon; #ifdef KTIKZ_USE_KDE -#include +# include class ToggleAction : public KToggleAction { - Q_OBJECT + Q_OBJECT public: - explicit ToggleAction(QObject *parent, const QString &name = QString()); - ToggleAction(const QString &text, QObject *parent, const QString &name = QString()); - ToggleAction(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); + explicit ToggleAction(QObject *parent, const QString &name = QString()); + ToggleAction(const QString &text, QObject *parent, const QString &name = QString()); + ToggleAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name = QString()); }; #else -#include -#include +# include +# include class ToggleAction : public QAction { - Q_OBJECT + Q_OBJECT public: - explicit ToggleAction(QObject *parent, const QString &name = QString()); - ToggleAction(const QString &text, QObject *parent, const QString &name = QString()); - ToggleAction(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); + explicit ToggleAction(QObject *parent, const QString &name = QString()); + ToggleAction(const QString &text, QObject *parent, const QString &name = QString()); + ToggleAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name = QString()); private: - void init(const QString &name); + void init(const QString &name); }; #endif diff --git a/common/utils/toolbar.cpp b/common/utils/toolbar.cpp index dae3123..39f9d53 100644 --- a/common/utils/toolbar.cpp +++ b/common/utils/toolbar.cpp @@ -19,42 +19,37 @@ #include "toolbar.h" #ifdef KTIKZ_USE_KDE -ToolBar::ToolBar(const QString &objectName, QWidget *parent) - : KToolBar(objectName, parent) -{ -} +ToolBar::ToolBar(const QString &objectName, QWidget *parent) : KToolBar(objectName, parent) { } #else -#include +# include -ToolBar::ToolBar(const QString &objectName, QWidget *parent) - : QToolBar(parent) +ToolBar::ToolBar(const QString &objectName, QWidget *parent) : QToolBar(parent) { - setObjectName(objectName); - setToolBarStyle(); + setObjectName(objectName); + setToolBarStyle(); } void ToolBar::setToolBarStyle() { - QSettings settings; - settings.beginGroup(QLatin1String("MainWindow")); + QSettings settings; + settings.beginGroup(QLatin1String("MainWindow")); - const int toolBarStyleNumber = settings.value(QLatin1String("ToolBarStyle"), 0).toInt(); - Qt::ToolButtonStyle toolBarStyle = Qt::ToolButtonIconOnly; - switch (toolBarStyleNumber) - { - case 0: - toolBarStyle = Qt::ToolButtonIconOnly; - break; - case 1: - toolBarStyle = Qt::ToolButtonTextOnly; - break; - case 2: - toolBarStyle = Qt::ToolButtonTextBesideIcon; - break; - case 3: - toolBarStyle = Qt::ToolButtonTextUnderIcon; - break; - } - setToolButtonStyle(toolBarStyle); + const int toolBarStyleNumber = settings.value(QLatin1String("ToolBarStyle"), 0).toInt(); + Qt::ToolButtonStyle toolBarStyle = Qt::ToolButtonIconOnly; + switch (toolBarStyleNumber) { + case 0: + toolBarStyle = Qt::ToolButtonIconOnly; + break; + case 1: + toolBarStyle = Qt::ToolButtonTextOnly; + break; + case 2: + toolBarStyle = Qt::ToolButtonTextBesideIcon; + break; + case 3: + toolBarStyle = Qt::ToolButtonTextUnderIcon; + break; + } + setToolButtonStyle(toolBarStyle); } #endif diff --git a/common/utils/toolbar.h b/common/utils/toolbar.h index 3727d1f..1d34996 100644 --- a/common/utils/toolbar.h +++ b/common/utils/toolbar.h @@ -20,28 +20,28 @@ #define KTIKZ_TOOLBAR_H #ifdef KTIKZ_USE_KDE -#include +# include class ToolBar : public KToolBar { - Q_OBJECT + Q_OBJECT public: - explicit ToolBar(const QString &objectName, QWidget *parent); + explicit ToolBar(const QString &objectName, QWidget *parent); }; #else -#include -#include +# include +# include class ToolBar : public QToolBar { - Q_OBJECT + Q_OBJECT public: - explicit ToolBar(const QString &objectName, QWidget *parent); + explicit ToolBar(const QString &objectName, QWidget *parent); private: - void setToolBarStyle(); + void setToolBarStyle(); }; #endif diff --git a/common/utils/url.cpp b/common/utils/url.cpp index 6eacab1..8f28099 100644 --- a/common/utils/url.cpp +++ b/common/utils/url.cpp @@ -20,36 +20,32 @@ #include -Url::Url() : QUrl() -{ -} +Url::Url() : QUrl() { } Url::Url(const QString &fileName) : QUrl(QUrl::fromUserInput(fileName)) { -// if (fileName.startsWith(QLatin1String("file://"))) -// setUrl(fileName); -// else -// setPath(fileName); + // if (fileName.startsWith(QLatin1String("file://"))) + // setUrl(fileName); + // else + // setPath(fileName); } -Url::Url(const QUrl &url) : QUrl(url) -{ -} +Url::Url(const QUrl &url) : QUrl(url) { } QString Url::pathOrUrl() const { #ifdef Q_OS_WIN32 - return QUrl::toString(); + return QUrl::toString(); #else - return QUrl::path(); + return QUrl::path(); #endif } QString Url::path() const { #ifdef Q_OS_WIN32 - return QUrl::toString(); + return QUrl::toString(); #else - return QUrl::path(); + return QUrl::path(); #endif } diff --git a/common/utils/url.h b/common/utils/url.h index d986bfe..89395b5 100644 --- a/common/utils/url.h +++ b/common/utils/url.h @@ -24,12 +24,12 @@ class Url : public QUrl { public: - Url(); - explicit Url(const QString &fileName); - Url(const QUrl &url); + Url(); + explicit Url(const QString &fileName); + Url(const QUrl &url); - QString pathOrUrl() const; - QString path() const; + QString pathOrUrl() const; + QString path() const; }; #endif diff --git a/common/utils/urlcompletion.h b/common/utils/urlcompletion.h index 98fb56b..0694b5c 100644 --- a/common/utils/urlcompletion.h +++ b/common/utils/urlcompletion.h @@ -20,30 +20,27 @@ #define KTIKZ_URLCOMPLETION_H #ifdef KTIKZ_USE_KDE -#include +# include class UrlCompletion : public KUrlCompletion { public: - explicit UrlCompletion(QObject *parent = 0) : KUrlCompletion() - { - Q_UNUSED(parent); - } + explicit UrlCompletion(QObject *parent = 0) : KUrlCompletion() { Q_UNUSED(parent); } }; #else -#include -#include +# include +# include class UrlCompletion : public QCompleter { public: - explicit UrlCompletion(QObject *parent = 0) : QCompleter(parent) - { - QFileSystemModel *fileSystemModel = new QFileSystemModel(this); - fileSystemModel->setRootPath(QDir::rootPath()); // slow - setModel(fileSystemModel); - setCompletionMode(QCompleter::PopupCompletion); - } + explicit UrlCompletion(QObject *parent = 0) : QCompleter(parent) + { + QFileSystemModel *fileSystemModel = new QFileSystemModel(this); + fileSystemModel->setRootPath(QDir::rootPath()); // slow + setModel(fileSystemModel); + setCompletionMode(QCompleter::PopupCompletion); + } }; #endif diff --git a/common/utils/zoomaction.cpp b/common/utils/zoomaction.cpp index 4b0835a..817da7f 100644 --- a/common/utils/zoomaction.cpp +++ b/common/utils/zoomaction.cpp @@ -24,122 +24,117 @@ static const qreal s_minZoomFactor = 0.1; static const qreal s_maxZoomFactor = 6; -ZoomAction::ZoomAction(QObject *parent, const QString &name) - : SelectAction(parent, name) +ZoomAction::ZoomAction(QObject *parent, const QString &name) : SelectAction(parent, name) { - init(); + init(); } ZoomAction::ZoomAction(const QString &text, QObject *parent, const QString &name) - : SelectAction(text, parent, name) + : SelectAction(text, parent, name) { - init(); + init(); } ZoomAction::ZoomAction(const Icon &icon, const QString &text, QObject *parent, const QString &name) - : SelectAction(icon, text, parent, name) + : SelectAction(icon, text, parent, name) { - init(); + init(); } void ZoomAction::init() { - setEditable(true); - setToolTip(tr("Select or insert zoom factor here")); - setWhatsThis(tr("

Select the zoom factor here. " - "Alternatively, you can also introduce a zoom factor and " - "press Enter.

")); - setCurrentZoomFactor(); - connect(this, SIGNAL(triggered(QString)), this, SLOT(setZoomFactor(QString))); + setEditable(true); + setToolTip(tr("Select or insert zoom factor here")); + setWhatsThis(tr("

Select the zoom factor here. " + "Alternatively, you can also introduce a zoom factor and " + "press Enter.

")); + setCurrentZoomFactor(); + connect(this, SIGNAL(triggered(QString)), this, SLOT(setZoomFactor(QString))); } -ZoomAction::~ZoomAction() -{ -} +ZoomAction::~ZoomAction() { } qreal ZoomAction::minZoomFactor() const { - return s_minZoomFactor; + return s_minZoomFactor; } qreal ZoomAction::maxZoomFactor() const { - return s_maxZoomFactor; + return s_maxZoomFactor; } static QString formatZoomFactor(qreal zoomFactor) { - QString zoomFactorText = GlobalLocale::formatNumber(zoomFactor, 2); - const QString decimalSymbol = GlobalLocale::decimalSymbol(); + QString zoomFactorText = GlobalLocale::formatNumber(zoomFactor, 2); + const QString decimalSymbol = GlobalLocale::decimalSymbol(); - zoomFactorText.remove(decimalSymbol + QLatin1String("00")); - // remove trailing zero in numbers like 12.30 - if (zoomFactorText.endsWith(QLatin1Char('0')) - && zoomFactorText.indexOf(decimalSymbol) >= 0) - zoomFactorText.chop(1); + zoomFactorText.remove(decimalSymbol + QLatin1String("00")); + // remove trailing zero in numbers like 12.30 + if (zoomFactorText.endsWith(QLatin1Char('0')) && zoomFactorText.indexOf(decimalSymbol) >= 0) + zoomFactorText.chop(1); - zoomFactorText += QLatin1Char('%'); - return zoomFactorText; + zoomFactorText += QLatin1Char('%'); + return zoomFactorText; } void ZoomAction::setCurrentZoomFactor(qreal newZoomFactor) { - const qreal zoomFactorArray[] = {12.50, 25, 50, 75, 100, 125, 150, 200, 250, 300}; - const int zoomFactorNumber = 10; - QStringList zoomFactorList; - int newZoomFactorPosition = -1; - bool addNewZoomFactor = true; - - if (newZoomFactor < s_minZoomFactor || newZoomFactor > s_maxZoomFactor) - addNewZoomFactor = false; - - newZoomFactor *= 100; - for (int i = 0; i < zoomFactorNumber; ++i) - { - if (addNewZoomFactor && newZoomFactor < zoomFactorArray[i]) - { - zoomFactorList << formatZoomFactor(newZoomFactor); - newZoomFactorPosition = i; - addNewZoomFactor = false; - } - else if (newZoomFactor == zoomFactorArray[i]) - { - newZoomFactorPosition = i; - addNewZoomFactor = false; - } - zoomFactorList << formatZoomFactor(zoomFactorArray[i]); - } - if (addNewZoomFactor) - { - zoomFactorList << formatZoomFactor(newZoomFactor); - newZoomFactorPosition = zoomFactorNumber; - } - - disconnect(this, SIGNAL(triggered(QString)), this, SLOT(setZoomFactor(QString))); - removeAllActions(); - setItems(zoomFactorList); - if (newZoomFactorPosition >= 0) - setCurrentItem(newZoomFactorPosition); - connect(this, SIGNAL(triggered(QString)), this, SLOT(setZoomFactor(QString))); + const qreal zoomFactorArray[] = { 12.50, 25, 50, 75, 100, 125, 150, 200, 250, 300 }; + const int zoomFactorNumber = 10; + QStringList zoomFactorList; + int newZoomFactorPosition = -1; + bool addNewZoomFactor = true; + + if (newZoomFactor < s_minZoomFactor || newZoomFactor > s_maxZoomFactor) + addNewZoomFactor = false; + + newZoomFactor *= 100; + for (int i = 0; i < zoomFactorNumber; ++i) { + if (addNewZoomFactor && newZoomFactor < zoomFactorArray[i]) { + zoomFactorList << formatZoomFactor(newZoomFactor); + newZoomFactorPosition = i; + addNewZoomFactor = false; + } else if (newZoomFactor == zoomFactorArray[i]) { + newZoomFactorPosition = i; + addNewZoomFactor = false; + } + zoomFactorList << formatZoomFactor(zoomFactorArray[i]); + } + if (addNewZoomFactor) { + zoomFactorList << formatZoomFactor(newZoomFactor); + newZoomFactorPosition = zoomFactorNumber; + } + + disconnect(this, SIGNAL(triggered(QString)), this, SLOT(setZoomFactor(QString))); + removeAllActions(); + setItems(zoomFactorList); + if (newZoomFactorPosition >= 0) + setCurrentItem(newZoomFactorPosition); + connect(this, SIGNAL(triggered(QString)), this, SLOT(setZoomFactor(QString))); } void ZoomAction::setZoomFactor(qreal zoomFactor) { - // adjust zoom factor - zoomFactor = qBound(s_minZoomFactor, zoomFactor, s_maxZoomFactor); - - // add current zoom factor to the list of zoom factors - const QString zoomFactorString = formatZoomFactor(zoomFactor * 100); - const int zoomFactorIndex = items().indexOf(zoomFactorString); - if (zoomFactorIndex >= 0) - setCurrentItem(zoomFactorIndex); - else - setCurrentZoomFactor(zoomFactor); - - Q_EMIT zoomFactorAdded(zoomFactor); + // adjust zoom factor + zoomFactor = qBound(s_minZoomFactor, zoomFactor, s_maxZoomFactor); + + // add current zoom factor to the list of zoom factors + const QString zoomFactorString = formatZoomFactor(zoomFactor * 100); + const int zoomFactorIndex = items().indexOf(zoomFactorString); + if (zoomFactorIndex >= 0) + setCurrentItem(zoomFactorIndex); + else + setCurrentZoomFactor(zoomFactor); + + Q_EMIT zoomFactorAdded(zoomFactor); } void ZoomAction::setZoomFactor(const QString &zoomFactorText) { - setZoomFactor(GlobalLocale::readNumber(QString(zoomFactorText).remove(QRegExp(QString(QLatin1String("[^\\d\\%1]*")).arg(GlobalLocale::decimalSymbol())))) / 100.0); + setZoomFactor(GlobalLocale::readNumber( + QString(zoomFactorText) + .remove(QRegExp(QString(QLatin1String("[^\\d\\%1]*")) + .arg(GlobalLocale::decimalSymbol())))) + / 100.0); } diff --git a/common/utils/zoomaction.h b/common/utils/zoomaction.h index 63e9516..3027b54 100644 --- a/common/utils/zoomaction.h +++ b/common/utils/zoomaction.h @@ -25,27 +25,28 @@ class Icon; class ZoomAction : public SelectAction { - Q_OBJECT + Q_OBJECT public: - explicit ZoomAction(QObject *parent, const QString &name = QString()); - ZoomAction(const QString &text, QObject *parent, const QString &name = QString()); - ZoomAction(const Icon &icon, const QString &text, QObject *parent, const QString &name = QString()); - ~ZoomAction(); + explicit ZoomAction(QObject *parent, const QString &name = QString()); + ZoomAction(const QString &text, QObject *parent, const QString &name = QString()); + ZoomAction(const Icon &icon, const QString &text, QObject *parent, + const QString &name = QString()); + ~ZoomAction(); - qreal minZoomFactor() const; - qreal maxZoomFactor() const; - void setZoomFactor(qreal zoomFactor); + qreal minZoomFactor() const; + qreal maxZoomFactor() const; + void setZoomFactor(qreal zoomFactor); Q_SIGNALS: - void zoomFactorAdded(qreal zoomFactor); + void zoomFactorAdded(qreal zoomFactor); private Q_SLOTS: - void setZoomFactor(const QString &zoomFactorText); + void setZoomFactor(const QString &zoomFactorText); private: - void init(); - void setCurrentZoomFactor(qreal newZoomFactor = 1); + void init(); + void setCurrentZoomFactor(qreal newZoomFactor = 1); }; #endif diff --git a/part/browserextension.cpp b/part/browserextension.cpp index 489dce2..8c3ccb4 100644 --- a/part/browserextension.cpp +++ b/part/browserextension.cpp @@ -23,25 +23,24 @@ #include "../common/tikzpreviewcontroller.h" -namespace KtikZ -{ +namespace KtikZ { -BrowserExtension::BrowserExtension(KParts::ReadOnlyPart *part, TikzPreviewController *tikzPreviewController) - : KParts::BrowserExtension(part) +BrowserExtension::BrowserExtension(KParts::ReadOnlyPart *part, + TikzPreviewController *tikzPreviewController) + : KParts::BrowserExtension(part) { - m_tikzPreviewController = tikzPreviewController; - emit enableAction("print", true); - QString iconPath = KIconLoader::global()->iconPath(QStringLiteral("text-x-pgf"), KIconLoader::SizeSmall); - emit setIconUrl(QUrl::fromLocalFile(iconPath)); + m_tikzPreviewController = tikzPreviewController; + emit enableAction("print", true); + QString iconPath = + KIconLoader::global()->iconPath(QStringLiteral("text-x-pgf"), KIconLoader::SizeSmall); + emit setIconUrl(QUrl::fromLocalFile(iconPath)); } -BrowserExtension::~BrowserExtension() -{ -} +BrowserExtension::~BrowserExtension() { } void BrowserExtension::print() { - m_tikzPreviewController->printImage(); + m_tikzPreviewController->printImage(); } } // namespace KtikZ diff --git a/part/browserextension.h b/part/browserextension.h index 000d7ce..47e5bbf 100644 --- a/part/browserextension.h +++ b/part/browserextension.h @@ -23,21 +23,20 @@ class TikzPreviewController; -namespace KtikZ -{ +namespace KtikZ { class BrowserExtension : public KParts::BrowserExtension { - Q_OBJECT + Q_OBJECT public: - BrowserExtension(KParts::ReadOnlyPart*, TikzPreviewController *tikzPreviewController); - ~BrowserExtension(); + BrowserExtension(KParts::ReadOnlyPart *, TikzPreviewController *tikzPreviewController); + ~BrowserExtension(); private Q_SLOTS: - void print(); + void print(); private: - TikzPreviewController *m_tikzPreviewController; + TikzPreviewController *m_tikzPreviewController; }; } // namespace KtikZ diff --git a/part/configdialog.cpp b/part/configdialog.cpp index f188f8f..6baf289 100644 --- a/part/configdialog.cpp +++ b/part/configdialog.cpp @@ -27,89 +27,95 @@ #include "configgeneralwidget.h" -namespace KtikZ -{ +namespace KtikZ { -PartConfigDialog::PartConfigDialog(QWidget *parent) - : QDialog(parent) +PartConfigDialog::PartConfigDialog(QWidget *parent) : QDialog(parent) { - setWindowTitle(i18nc("@title:window", "Configure KtikZ Viewer")); - m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::RestoreDefaults|QDialogButtonBox::Apply); - - QVBoxLayout *mainLayout = new QVBoxLayout; - - m_configGeneralWidget = new PartConfigGeneralWidget(this); - mainLayout->addWidget(viewerWidget()); - mainLayout->addWidget(m_configGeneralWidget); - - QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - //PORTING SCRIPT: WARNING mainLayout->addWidget(buttonBox) must be last item in layout. Please move it. - mainLayout->addWidget(m_buttonBox); - - setLayout(mainLayout); - - connect(m_buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(writeSettings())); - connect(okButton, SIGNAL(clicked()), this, SLOT(writeSettings())); - connect(m_buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), this, SLOT(setDefaults())); - connect(m_configGeneralWidget, SIGNAL(changed(bool)), this, SLOT(buttonBox->button(QDialogButtonBox::Apply)->setEnabled(bool))); - m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); + setWindowTitle(i18nc("@title:window", "Configure KtikZ Viewer")); + m_buttonBox = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel + | QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Apply); + + QVBoxLayout *mainLayout = new QVBoxLayout; + + m_configGeneralWidget = new PartConfigGeneralWidget(this); + mainLayout->addWidget(viewerWidget()); + mainLayout->addWidget(m_configGeneralWidget); + + QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + // PORTING SCRIPT: WARNING mainLayout->addWidget(buttonBox) must be last item in layout. Please + // move it. + mainLayout->addWidget(m_buttonBox); + + setLayout(mainLayout); + + connect(m_buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, + SLOT(writeSettings())); + connect(okButton, SIGNAL(clicked()), this, SLOT(writeSettings())); + connect(m_buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), this, + SLOT(setDefaults())); + connect(m_configGeneralWidget, SIGNAL(changed(bool)), this, + SLOT(buttonBox->button(QDialogButtonBox::Apply)->setEnabled(bool))); + m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); } -PartConfigDialog::~PartConfigDialog() -{ -} +PartConfigDialog::~PartConfigDialog() { } QWidget *PartConfigDialog::viewerWidget() { - QGroupBox *viewerGroupBox = new QGroupBox(i18nc("@title:group", "Viewer")); - QVBoxLayout *viewerLayout = new QVBoxLayout(viewerGroupBox); - m_watchFileCheckBox = new QCheckBox(i18nc("@option:check", "&Reload document on file change")); - m_watchFileCheckBox->setObjectName("watchFileCheckBox"); - m_watchFileCheckBox->setWhatsThis(i18nc("@info:whatsthis", "When this option is checked, " - "the TikZ image will be reloaded each time that the file is modified " - "by another program.")); - viewerLayout->addWidget(m_watchFileCheckBox); - - connect(m_watchFileCheckBox, SIGNAL(toggled(bool)), this, SLOT(setModified())); - - return viewerGroupBox; + QGroupBox *viewerGroupBox = new QGroupBox(i18nc("@title:group", "Viewer")); + QVBoxLayout *viewerLayout = new QVBoxLayout(viewerGroupBox); + m_watchFileCheckBox = new QCheckBox(i18nc("@option:check", "&Reload document on file change")); + m_watchFileCheckBox->setObjectName("watchFileCheckBox"); + m_watchFileCheckBox->setWhatsThis( + i18nc("@info:whatsthis", + "When this option is checked, " + "the TikZ image will be reloaded each time that the file is modified " + "by another program.")); + viewerLayout->addWidget(m_watchFileCheckBox); + + connect(m_watchFileCheckBox, SIGNAL(toggled(bool)), this, SLOT(setModified())); + + return viewerGroupBox; } void PartConfigDialog::setDefaults() { - m_configGeneralWidget->setDefaults(); - m_watchFileCheckBox->setChecked(true); + m_configGeneralWidget->setDefaults(); + m_watchFileCheckBox->setChecked(true); } void PartConfigDialog::readSettings() { - m_configGeneralWidget->readSettings(); + m_configGeneralWidget->readSettings(); - QSettings settings(ORGNAME, APPNAME); - m_watchFileCheckBox->setChecked(settings.value("WatchFile", true).toBool()); + QSettings settings(ORGNAME, APPNAME); + m_watchFileCheckBox->setChecked(settings.value("WatchFile", true).toBool()); } void PartConfigDialog::setModified() { - QWidget *sendingWidget = qobject_cast(sender()); - QSettings settings(ORGNAME, APPNAME); - if (sendingWidget->objectName() == QLatin1String("watchFileCheckBox")) - m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(m_watchFileCheckBox->isChecked() != settings.value("WatchFile", true).toBool()); + QWidget *sendingWidget = qobject_cast(sender()); + QSettings settings(ORGNAME, APPNAME); + if (sendingWidget->objectName() == QLatin1String("watchFileCheckBox")) + m_buttonBox->button(QDialogButtonBox::Apply) + ->setEnabled(m_watchFileCheckBox->isChecked() + != settings.value("WatchFile", true).toBool()); } void PartConfigDialog::writeSettings() { - m_configGeneralWidget->writeSettings(); + m_configGeneralWidget->writeSettings(); - QSettings settings(ORGNAME, APPNAME); - settings.setValue("WatchFile", m_watchFileCheckBox->isChecked()); + QSettings settings(ORGNAME, APPNAME); + settings.setValue("WatchFile", m_watchFileCheckBox->isChecked()); - m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); - emit settingsChanged("preferences"); + m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false); + emit settingsChanged("preferences"); } } // namespace KtikZ diff --git a/part/configdialog.h b/part/configdialog.h index 5321828..73d21f4 100644 --- a/part/configdialog.h +++ b/part/configdialog.h @@ -24,37 +24,36 @@ class QDialogButtonBox; class QCheckBox; -namespace KtikZ -{ +namespace KtikZ { class PartConfigGeneralWidget; class PartConfigDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit PartConfigDialog(QWidget *parent); - ~PartConfigDialog(); + explicit PartConfigDialog(QWidget *parent); + ~PartConfigDialog(); - void readSettings(); + void readSettings(); public slots: - void setDefaults(); - void writeSettings(); + void setDefaults(); + void writeSettings(); signals: - void settingsChanged(const QString &dialogName); + void settingsChanged(const QString &dialogName); private slots: - void setModified(); + void setModified(); private: - QWidget *viewerWidget(); + QWidget *viewerWidget(); - PartConfigGeneralWidget *m_configGeneralWidget; - QDialogButtonBox *m_buttonBox; - QCheckBox *m_watchFileCheckBox; + PartConfigGeneralWidget *m_configGeneralWidget; + QDialogButtonBox *m_buttonBox; + QCheckBox *m_watchFileCheckBox; }; } // namespace KtikZ diff --git a/part/configgeneralwidget.cpp b/part/configgeneralwidget.cpp index 8b70126..a66161e 100644 --- a/part/configgeneralwidget.cpp +++ b/part/configgeneralwidget.cpp @@ -20,63 +20,65 @@ #include -namespace KtikZ -{ +namespace KtikZ { -PartConfigGeneralWidget::PartConfigGeneralWidget(QWidget *parent) - : QWidget(parent) +PartConfigGeneralWidget::PartConfigGeneralWidget(QWidget *parent) : QWidget(parent) { - ui.setupUi(this); - ui.verticalLayout->setContentsMargins(0, 0, 0, 0); + ui.setupUi(this); + ui.verticalLayout->setContentsMargins(0, 0, 0, 0); } void PartConfigGeneralWidget::setDefaults() { - ui.latexUrlRequester->setText("pdflatex"); - ui.pdftopsUrlRequester->setText("pdftops"); - ui.editorUrlRequester->setText("kwrite"); - ui.replaceEdit->setText("<>"); + ui.latexUrlRequester->setText("pdflatex"); + ui.pdftopsUrlRequester->setText("pdftops"); + ui.editorUrlRequester->setText("kwrite"); + ui.replaceEdit->setText("<>"); } void PartConfigGeneralWidget::readSettings(const QString &settingsGroup) { - QSettings settings(ORGNAME, APPNAME); - settings.beginGroup(settingsGroup); - ui.latexUrlRequester->setText(settings.value("LatexCommand", "pdflatex").toString()); - ui.pdftopsUrlRequester->setText(settings.value("PdftopsCommand", "pdftops").toString()); - ui.editorUrlRequester->setText(settings.value("TemplateEditor", "kwrite").toString()); - ui.replaceEdit->setText(settings.value("TemplateReplaceText", "<>").toString()); - settings.endGroup(); + QSettings settings(ORGNAME, APPNAME); + settings.beginGroup(settingsGroup); + ui.latexUrlRequester->setText(settings.value("LatexCommand", "pdflatex").toString()); + ui.pdftopsUrlRequester->setText(settings.value("PdftopsCommand", "pdftops").toString()); + ui.editorUrlRequester->setText(settings.value("TemplateEditor", "kwrite").toString()); + ui.replaceEdit->setText(settings.value("TemplateReplaceText", "<>").toString()); + settings.endGroup(); - connect(ui.latexUrlRequester, SIGNAL(textChanged(QString)), this, SLOT(setModified())); - connect(ui.pdftopsUrlRequester, SIGNAL(textChanged(QString)), this, SLOT(setModified())); - connect(ui.editorUrlRequester, SIGNAL(textChanged(QString)), this, SLOT(setModified())); - connect(ui.replaceEdit, SIGNAL(textChanged(QString)), this, SLOT(setModified())); + connect(ui.latexUrlRequester, SIGNAL(textChanged(QString)), this, SLOT(setModified())); + connect(ui.pdftopsUrlRequester, SIGNAL(textChanged(QString)), this, SLOT(setModified())); + connect(ui.editorUrlRequester, SIGNAL(textChanged(QString)), this, SLOT(setModified())); + connect(ui.replaceEdit, SIGNAL(textChanged(QString)), this, SLOT(setModified())); } void PartConfigGeneralWidget::setModified() { - QWidget *sendingWidget = qobject_cast(sender()); - QSettings settings(ORGNAME, APPNAME); - if (sendingWidget->objectName() == QLatin1String("latexUrlRequester")) - emit changed(ui.latexUrlRequester->text() != settings.value("LatexCommand", "pdflatex").toString()); - else if (sendingWidget->objectName() == QLatin1String("pdftopsUrlRequester")) - emit changed(ui.pdftopsUrlRequester->text() != settings.value("PdftopsCommand", "pdftops").toString()); - else if (sendingWidget->objectName() == QLatin1String("editorUrlRequester")) - emit changed(ui.editorUrlRequester->text() != settings.value("TemplateEditor", "kwrite").toString()); - else if (sendingWidget->objectName() == QLatin1String("replaceEdit")) - emit changed(ui.replaceEdit->text() != settings.value("TemplateReplaceText", "<>").toString()); + QWidget *sendingWidget = qobject_cast(sender()); + QSettings settings(ORGNAME, APPNAME); + if (sendingWidget->objectName() == QLatin1String("latexUrlRequester")) + emit changed(ui.latexUrlRequester->text() + != settings.value("LatexCommand", "pdflatex").toString()); + else if (sendingWidget->objectName() == QLatin1String("pdftopsUrlRequester")) + emit changed(ui.pdftopsUrlRequester->text() + != settings.value("PdftopsCommand", "pdftops").toString()); + else if (sendingWidget->objectName() == QLatin1String("editorUrlRequester")) + emit changed(ui.editorUrlRequester->text() + != settings.value("TemplateEditor", "kwrite").toString()); + else if (sendingWidget->objectName() == QLatin1String("replaceEdit")) + emit changed(ui.replaceEdit->text() + != settings.value("TemplateReplaceText", "<>").toString()); } void PartConfigGeneralWidget::writeSettings(const QString &settingsGroup) { - QSettings settings(ORGNAME, APPNAME); - settings.beginGroup(settingsGroup); - settings.setValue("LatexCommand", ui.latexUrlRequester->text()); - settings.setValue("PdftopsCommand", ui.pdftopsUrlRequester->text()); - settings.setValue("TemplateEditor", ui.editorUrlRequester->text()); - settings.setValue("TemplateReplaceText", ui.replaceEdit->text()); - settings.endGroup(); + QSettings settings(ORGNAME, APPNAME); + settings.beginGroup(settingsGroup); + settings.setValue("LatexCommand", ui.latexUrlRequester->text()); + settings.setValue("PdftopsCommand", ui.pdftopsUrlRequester->text()); + settings.setValue("TemplateEditor", ui.editorUrlRequester->text()); + settings.setValue("TemplateReplaceText", ui.replaceEdit->text()); + settings.endGroup(); } } // namespace KtikZ diff --git a/part/configgeneralwidget.h b/part/configgeneralwidget.h index de30540..0845769 100644 --- a/part/configgeneralwidget.h +++ b/part/configgeneralwidget.h @@ -22,28 +22,27 @@ #include #include "ui_configgeneralwidget.h" -namespace KtikZ -{ +namespace KtikZ { class PartConfigGeneralWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit PartConfigGeneralWidget(QWidget *parent = 0); + explicit PartConfigGeneralWidget(QWidget *parent = 0); - void setDefaults(); - void readSettings(const QString &settingsGroup = QString()); - void writeSettings(const QString &settingsGroup = QString()); + void setDefaults(); + void readSettings(const QString &settingsGroup = QString()); + void writeSettings(const QString &settingsGroup = QString()); signals: - void changed(bool isChanged); + void changed(bool isChanged); protected: - Ui::PartConfigGeneralWidget ui; + Ui::PartConfigGeneralWidget ui; private slots: - void setModified(); + void setModified(); }; } // namespace KtikZ diff --git a/part/part.cpp b/part/part.cpp index be6077e..a3808a5 100644 --- a/part/part.cpp +++ b/part/part.cpp @@ -62,290 +62,291 @@ #include "../common/utils/action.h" #include "browserextension.h" -namespace KtikZ -{ +namespace KtikZ { Part::Part(QWidget *parentWidget, QObject *parent, const QVariantList &args) - : KParts::ReadOnlyPart(parent) + : KParts::ReadOnlyPart(parent) { - Q_UNUSED(args); + Q_UNUSED(args); - // dirty hack: make sure that the "Export" menu and the "Template" widget are translated - QTranslator *translator = createTranslator("qtikz"); - qApp->installTranslator(translator); + // dirty hack: make sure that the "Export" menu and the "Template" widget are translated + QTranslator *translator = createTranslator("qtikz"); + qApp->installTranslator(translator); - setComponentData(KAboutData("ktikzpart", "KtikZ", APPVERSION)); -// setComponentData(ktikzPartFactory::componentData()); // make sure that the actions of this kpart go in a separate section labeled "KtikZ Viewer" (as defined in K_EXPORT_PLUGIN above) in the "Configure Shortcuts" dialog + setComponentData(KAboutData("ktikzpart", "KtikZ", APPVERSION)); + // setComponentData(ktikzPartFactory::componentData()); // make sure that the actions of this + // kpart go in a separate section labeled "KtikZ Viewer" (as defined in K_EXPORT_PLUGIN above) + // in the "Configure Shortcuts" dialog - m_configDialog = 0; + m_configDialog = 0; - Action::setActionCollection(actionCollection()); - m_tikzPreviewController = new TikzPreviewController(this); + Action::setActionCollection(actionCollection()); + m_tikzPreviewController = new TikzPreviewController(this); - QWidget *mainWidget = new QWidget(parentWidget); - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->setSpacing(0); - mainLayout->setMargin(0); - mainLayout->addWidget(m_tikzPreviewController->templateWidget()); - mainLayout->addWidget(m_tikzPreviewController->tikzPreview()); - mainWidget->setLayout(mainLayout); - setWidget(mainWidget); + QWidget *mainWidget = new QWidget(parentWidget); + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->setSpacing(0); + mainLayout->setMargin(0); + mainLayout->addWidget(m_tikzPreviewController->templateWidget()); + mainLayout->addWidget(m_tikzPreviewController->tikzPreview()); + mainWidget->setLayout(mainLayout); + setWidget(mainWidget); - createActions(); + createActions(); - // document watcher and reloader - m_watcher = new KDirWatch(this); - connect(m_watcher, SIGNAL(dirty(QString)), this, SLOT(slotFileDirty(QString))); - m_dirtyHandler = new QTimer(this); - m_dirtyHandler->setSingleShot(true); - connect(m_dirtyHandler, SIGNAL(timeout()), this, SLOT(slotDoFileDirty())); + // document watcher and reloader + m_watcher = new KDirWatch(this); + connect(m_watcher, SIGNAL(dirty(QString)), this, SLOT(slotFileDirty(QString))); + m_dirtyHandler = new QTimer(this); + m_dirtyHandler->setSingleShot(true); + connect(m_dirtyHandler, SIGNAL(timeout()), this, SLOT(slotDoFileDirty())); - new BrowserExtension(this, m_tikzPreviewController); // needed to be able to use Konqueror's "Print" action + new BrowserExtension( + this, m_tikzPreviewController); // needed to be able to use Konqueror's "Print" action - setXMLFile("ktikzpart/ktikzpart.rc"); + setXMLFile("ktikzpart/ktikzpart.rc"); - applySettings(); + applySettings(); } Part::~Part() { - delete m_tikzPreviewController; + delete m_tikzPreviewController; } QWidget *Part::widget() { - return KParts::ReadOnlyPart::widget(); + return KParts::ReadOnlyPart::widget(); } KAboutData *Part::createAboutData() { - KAboutData *aboutData = new KAboutData(QStringLiteral("ktikz"),i18n("KtikZ"), APPVERSION); - aboutData->setShortDescription(i18n("A TikZ Viewer")); - aboutData->setLicense(KAboutLicense::GPL_V2); - aboutData->setCopyrightStatement(i18n("Copyright 2007-2014 Florian Hackenberger, Glad Deschrijver")); - aboutData->setOtherText(i18n("This is a plugin for viewing TikZ (from the LaTeX pgf package) diagrams.")); - aboutData->setBugAddress("florian@hackenberger.at"); - aboutData->addAuthor(i18n("Florian Hackenberger"), i18n("Maintainer"), "florian@hackenberger.at"); - aboutData->addAuthor(i18n("Glad Deschrijver"), i18n("Developer"), "glad.deschrijver@gmail.com"); - return aboutData; + KAboutData *aboutData = new KAboutData(QStringLiteral("ktikz"), i18n("KtikZ"), APPVERSION); + aboutData->setShortDescription(i18n("A TikZ Viewer")); + aboutData->setLicense(KAboutLicense::GPL_V2); + aboutData->setCopyrightStatement( + i18n("Copyright 2007-2014 Florian Hackenberger, Glad Deschrijver")); + aboutData->setOtherText( + i18n("This is a plugin for viewing TikZ (from the LaTeX pgf package) diagrams.")); + aboutData->setBugAddress("florian@hackenberger.at"); + aboutData->addAuthor(i18n("Florian Hackenberger"), i18n("Maintainer"), + "florian@hackenberger.at"); + aboutData->addAuthor(i18n("Glad Deschrijver"), i18n("Developer"), "glad.deschrijver@gmail.com"); + return aboutData; } void Part::showAboutDialog() { - KAboutApplicationDialog dlg(*(createAboutData()), widget()); - dlg.exec(); + KAboutApplicationDialog dlg(*(createAboutData()), widget()); + dlg.exec(); } void Part::createActions() { - // File - m_saveAsAction = actionCollection()->addAction(KStandardAction::SaveAs, this, SLOT(saveAs())); - m_saveAsAction->setWhatsThis(i18nc("@info:whatsthis", "Save the document under a new name.")); - - // Reload: we rely on Konqueror's "Reload" action instead of defining our own - - // Configure - QAction *action = KStandardAction::preferences(this, SLOT(configure()), actionCollection()); - action->setText(i18nc("@action", "Configure KtikZ Viewer...")); - - // Help - action = actionCollection()->addAction("help_about_ktikz"); - action->setText(i18n("About KtikZ Viewer")); - action->setIcon(QIcon::fromTheme("ktikz")); - connect(action, SIGNAL(triggered()), this, SLOT(showAboutDialog())); + // File + m_saveAsAction = actionCollection()->addAction(KStandardAction::SaveAs, this, SLOT(saveAs())); + m_saveAsAction->setWhatsThis( + i18nc("@info:whatsthis", "Save the document under a new name.")); + + // Reload: we rely on Konqueror's "Reload" action instead of defining our own + + // Configure + QAction *action = KStandardAction::preferences(this, SLOT(configure()), actionCollection()); + action->setText(i18nc("@action", "Configure KtikZ Viewer...")); + + // Help + action = actionCollection()->addAction("help_about_ktikz"); + action->setText(i18n("About KtikZ Viewer")); + action->setIcon(QIcon::fromTheme("ktikz")); + connect(action, SIGNAL(triggered()), this, SLOT(showAboutDialog())); } /***************************************************************************/ bool Part::openFile() { - const QString fileName = localFilePath(); - - QFile file(fileName); - if (!file.open(QFile::ReadOnly | QFile::Text)) - { - KMessageBox::error(widget(), i18nc("@info", "Cannot read file %1:%2", fileName, file.errorString()), i18nc("@title:window", "File Read Error")); - return false; - } - - QTextStream in(&file); - m_tikzCode = in.readAll(); - m_tikzPreviewController->generatePreview(); - - // set the file to the fileWatcher - if (url().isLocalFile()) - { - if (!m_watcher->contains(localFilePath())) - m_watcher->addFile(localFilePath()); - QFileInfo fi(localFilePath()); - if (!m_watcher->contains(fi.absolutePath())) - m_watcher->addDir(fi.absolutePath()); - } - m_fileWasRemoved = false; - - return true; + const QString fileName = localFilePath(); + + QFile file(fileName); + if (!file.open(QFile::ReadOnly | QFile::Text)) { + KMessageBox::error( + widget(), + i18nc("@info", + "Cannot read file %1:%2", + fileName, file.errorString()), + i18nc("@title:window", "File Read Error")); + return false; + } + + QTextStream in(&file); + m_tikzCode = in.readAll(); + m_tikzPreviewController->generatePreview(); + + // set the file to the fileWatcher + if (url().isLocalFile()) { + if (!m_watcher->contains(localFilePath())) + m_watcher->addFile(localFilePath()); + QFileInfo fi(localFilePath()); + if (!m_watcher->contains(fi.absolutePath())) + m_watcher->addDir(fi.absolutePath()); + } + m_fileWasRemoved = false; + + return true; } void Part::saveAs() { - const Url srcUrl = url(); - - QMimeDatabase db; - const QMimeType mimeType = db.mimeTypeForName("text/x-pgf"); - const QString tikzFilter = (mimeType.isValid()) ? - mimeType.globPatterns().join(" ") + '|' + mimeType.comment() - : "*.pgf *.tikz *.tex|" + i18nc("@item:inlistbox filter", "TikZ files"); - const QUrl dstUrl = QFileDialog::getSaveFileUrl(widget(), i18nc("@title:window", "Save TikZ Source File As"), - srcUrl, tikzFilter + "\n*|" + i18nc("@item:inlistbox filter", "All files")); - - if (!dstUrl.isValid()) - return; - - KIO::Job *job = KIO::file_copy(srcUrl, dstUrl, -1, KIO::Overwrite | KIO::HideProgressInfo); - connect(job, SIGNAL(result(KJob*)), this, SLOT(showJobError(KJob*))); + const Url srcUrl = url(); + + QMimeDatabase db; + const QMimeType mimeType = db.mimeTypeForName("text/x-pgf"); + const QString tikzFilter = (mimeType.isValid()) + ? mimeType.globPatterns().join(" ") + '|' + mimeType.comment() + : "*.pgf *.tikz *.tex|" + i18nc("@item:inlistbox filter", "TikZ files"); + const QUrl dstUrl = QFileDialog::getSaveFileUrl( + widget(), i18nc("@title:window", "Save TikZ Source File As"), srcUrl, + tikzFilter + "\n*|" + i18nc("@item:inlistbox filter", "All files")); + + if (!dstUrl.isValid()) + return; + + KIO::Job *job = KIO::file_copy(srcUrl, dstUrl, -1, KIO::Overwrite | KIO::HideProgressInfo); + connect(job, SIGNAL(result(KJob *)), this, SLOT(showJobError(KJob *))); } bool Part::closeUrl() { - if (url().isLocalFile()) - { - m_watcher->removeFile(localFilePath()); - QFileInfo fi(localFilePath()); - m_watcher->removeDir(fi.absolutePath()); - } + if (url().isLocalFile()) { + m_watcher->removeFile(localFilePath()); + QFileInfo fi(localFilePath()); + m_watcher->removeDir(fi.absolutePath()); + } - emit setWindowCaption(""); - m_fileWasRemoved = false; + emit setWindowCaption(""); + m_fileWasRemoved = false; - return KParts::ReadOnlyPart::closeUrl(); + return KParts::ReadOnlyPart::closeUrl(); } void Part::showJobError(KJob *job) { - if (job->error() != 0) - { - KIO::JobUiDelegate *ui = static_cast(static_cast(job)->uiDelegate()); - - if (!ui) - { - qCritical() << "Saving failed; job->ui() is null."; - return; - } - ui->setWindow(widget()); - ui->showErrorMessage(); - } + if (job->error() != 0) { + KIO::JobUiDelegate *ui = + static_cast(static_cast(job)->uiDelegate()); + + if (!ui) { + qCritical() << "Saving failed; job->ui() is null."; + return; + } + ui->setWindow(widget()); + ui->showErrorMessage(); + } } QString Part::tikzCode() const { - return m_tikzCode; + return m_tikzCode; } QUrl KtikZ::Part::url() const { - return KParts::ReadOnlyPart::url(); + return KParts::ReadOnlyPart::url(); } /***************************************************************************/ void Part::slotFileDirty(const QString &path) { - // The beauty of this is that each start cancels the previous one. - // This means that timeout() is only fired when there have - // no changes to the file for the last 750 milisecs. - // This ensures that we don't update on every other byte that gets - // written to the file. - if (path == localFilePath()) - { - m_dirtyHandler->start(750); - } - else - { - QFileInfo fi(localFilePath()); - if (fi.absolutePath() == path) - { - // Our parent has been dirtified - if (!QFile::exists(localFilePath())) - { - m_fileWasRemoved = true; - } - else if (m_fileWasRemoved && QFile::exists(localFilePath())) - { - // we need to watch the new file - m_watcher->removeFile(localFilePath()); - m_watcher->addFile(localFilePath()); - m_dirtyHandler->start(750); - } - } - } + // The beauty of this is that each start cancels the previous one. + // This means that timeout() is only fired when there have + // no changes to the file for the last 750 milisecs. + // This ensures that we don't update on every other byte that gets + // written to the file. + if (path == localFilePath()) { + m_dirtyHandler->start(750); + } else { + QFileInfo fi(localFilePath()); + if (fi.absolutePath() == path) { + // Our parent has been dirtified + if (!QFile::exists(localFilePath())) { + m_fileWasRemoved = true; + } else if (m_fileWasRemoved && QFile::exists(localFilePath())) { + // we need to watch the new file + m_watcher->removeFile(localFilePath()); + m_watcher->addFile(localFilePath()); + m_dirtyHandler->start(750); + } + } + } } void Part::slotDoFileDirty() { - m_tikzPreviewController->tikzPreview()->showErrorMessage(i18nc("@info:status", "Reloading the document...")); - - // close and (try to) reopen the document - if (!KParts::ReadOnlyPart::openUrl(url())) - { - // start watching the file again (since we dropped it on close) - m_watcher->addFile(localFilePath()); - m_dirtyHandler->start(750); - } + m_tikzPreviewController->tikzPreview()->showErrorMessage( + i18nc("@info:status", "Reloading the document...")); + + // close and (try to) reopen the document + if (!KParts::ReadOnlyPart::openUrl(url())) { + // start watching the file again (since we dropped it on close) + m_watcher->addFile(localFilePath()); + m_dirtyHandler->start(750); + } } /***************************************************************************/ void Part::applySettings() { - m_tikzPreviewController->applySettings(); - - // Watch File - QSettings settings(ORGNAME, APPNAME); - bool watchFile = settings.value("WatchFile", true).toBool(); - if (watchFile && m_watcher->isStopped()) - m_watcher->startScan(); - if (!watchFile && !m_watcher->isStopped()) - { - m_dirtyHandler->stop(); - m_watcher->stopScan(); - } + m_tikzPreviewController->applySettings(); + + // Watch File + QSettings settings(ORGNAME, APPNAME); + bool watchFile = settings.value("WatchFile", true).toBool(); + if (watchFile && m_watcher->isStopped()) + m_watcher->startScan(); + if (!watchFile && !m_watcher->isStopped()) { + m_dirtyHandler->stop(); + m_watcher->stopScan(); + } } void Part::configure() { - if (m_configDialog == 0) - { - m_configDialog = new PartConfigDialog(widget()); - connect(m_configDialog, SIGNAL(settingsChanged(QString)), this, SLOT(applySettings())); - } - m_configDialog->readSettings(); - m_configDialog->show(); + if (m_configDialog == 0) { + m_configDialog = new PartConfigDialog(widget()); + connect(m_configDialog, SIGNAL(settingsChanged(QString)), this, SLOT(applySettings())); + } + m_configDialog->readSettings(); + m_configDialog->show(); } /***************************************************************************/ /* The following are only used to translate the "Export" menu and "Template" widget */ -bool Part::findTranslator(QTranslator *translator, const QString &transName, const QString &transDir) +bool Part::findTranslator(QTranslator *translator, const QString &transName, + const QString &transDir) { - const QString qmFile = transName + ".qm"; - if (QFileInfo(QDir(transDir), qmFile).exists()) - return translator->load(qmFile, transDir); - return false; + const QString qmFile = transName + ".qm"; + if (QFileInfo(QDir(transDir), qmFile).exists()) + return translator->load(qmFile, transDir); + return false; } QTranslator *Part::createTranslator(const QString &transName) { - const QString locale = QLocale::languageToString(QLocale().language()); - const QString localeShort = locale.left(2).toLower(); + const QString locale = QLocale::languageToString(QLocale().language()); + const QString localeShort = locale.left(2).toLower(); - QTranslator *translator = new QTranslator(0); + QTranslator *translator = new QTranslator(0); #ifdef KTIKZ_TRANSLATIONS_INSTALL_DIR - const QDir qmPath(KTIKZ_TRANSLATIONS_INSTALL_DIR); - bool foundTranslator = findTranslator(translator, transName + '_' + locale, qmPath.absolutePath()); - if (!foundTranslator) - findTranslator(translator, transName + '_' + localeShort, qmPath.absolutePath()); + const QDir qmPath(KTIKZ_TRANSLATIONS_INSTALL_DIR); + bool foundTranslator = + findTranslator(translator, transName + '_' + locale, qmPath.absolutePath()); + if (!foundTranslator) + findTranslator(translator, transName + '_' + localeShort, qmPath.absolutePath()); #endif - return translator; + return translator; } K_PLUGIN_FACTORY(ktikzPartFactory, registerPlugin();) diff --git a/part/part.h b/part/part.h index ee08060..04dd463 100644 --- a/part/part.h +++ b/part/part.h @@ -30,8 +30,7 @@ class QTranslator; class TikzPreviewController; -namespace KtikZ -{ +namespace KtikZ { class PartConfigDialog; @@ -40,53 +39,52 @@ class PartConfigDialog; */ class Part : public KParts::ReadOnlyPart, public MainWidget { - Q_OBJECT + Q_OBJECT public: - explicit Part(QWidget *parentWidget, QObject *parent, const QVariantList &args); - virtual ~Part() Q_DECL_OVERRIDE; + explicit Part(QWidget *parentWidget, QObject *parent, const QVariantList &args); + virtual ~Part() Q_DECL_OVERRIDE; - static KAboutData *createAboutData(); - virtual QWidget *widget(); - QString tikzCode() const; - QUrl url() const; + static KAboutData *createAboutData(); + virtual QWidget *widget(); + QString tikzCode() const; + QUrl url() const; protected: - /** Reimplemented from KParts::PartBase. */ - bool openFile() Q_DECL_OVERRIDE; - bool closeUrl(); + /** Reimplemented from KParts::PartBase. */ + bool openFile() Q_DECL_OVERRIDE; + bool closeUrl(); private slots: - void showAboutDialog(); + void showAboutDialog(); - void saveAs(); - void showJobError(KJob *job); + void saveAs(); + void showJobError(KJob *job); - void slotFileDirty(const QString &path); - void slotDoFileDirty(); + void slotFileDirty(const QString &path); + void slotDoFileDirty(); - void applySettings(); - void configure(); + void applySettings(); + void configure(); private: - void createActions(); - bool findTranslator(QTranslator *translator, const QString &transName, const QString &transDir); - QTranslator *createTranslator(const QString &transName); + void createActions(); + bool findTranslator(QTranslator *translator, const QString &transName, const QString &transDir); + QTranslator *createTranslator(const QString &transName); - TikzPreviewController *m_tikzPreviewController; - PartConfigDialog *m_configDialog; + TikzPreviewController *m_tikzPreviewController; + PartConfigDialog *m_configDialog; - QAction *m_saveAsAction; + QAction *m_saveAsAction; - QString m_tikzCode; + QString m_tikzCode; - // document watcher (and reloader) variables - KDirWatch *m_watcher; - QTimer *m_dirtyHandler; - bool m_fileWasRemoved; + // document watcher (and reloader) variables + KDirWatch *m_watcher; + QTimer *m_dirtyHandler; + bool m_fileWasRemoved; }; } // namespace KtikZ - #endif