diff --git a/src/backends/python/pythonserver.cpp b/src/backends/python/pythonserver.cpp index be23a196..0dce0f1a 100644 --- a/src/backends/python/pythonserver.cpp +++ b/src/backends/python/pythonserver.cpp @@ -1,117 +1,117 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2015 Minh Ngo */ #include "pythonserver.h" #include PythonServer::PythonServer(QObject* parent) : QObject(parent), m_pModule(nullptr) { } namespace { QString pyObjectToQString(PyObject* obj) { #if PY_MAJOR_VERSION == 3 return QString::fromUtf8(PyUnicode_AsUTF8(obj)); #elif PY_MAJOR_VERSION == 2 return QString::fromLocal8Bit(PyString_AsString(obj)); #else #warning Unknown Python version #endif } } void PythonServer::login() { Py_InspectFlag = 1; Py_Initialize(); m_pModule = PyImport_AddModule("__main__"); - filePath = QLatin1String("python_cantor_worksheet"); + filePath = QStringLiteral("python_cantor_worksheet"); } void PythonServer::runPythonCommand(const QString& command) const { PyObject* py_dict = PyModule_GetDict(m_pModule); const char* prepareCommand = "import sys;\n"\ "class CatchOutPythonBackend:\n"\ " def __init__(self):\n"\ " self.value = ''\n"\ " def write(self, txt):\n"\ " self.value += txt\n"\ "outputPythonBackend = CatchOutPythonBackend()\n"\ "errorPythonBackend = CatchOutPythonBackend()\n"\ "sys.stdout = outputPythonBackend\n"\ "sys.stderr = errorPythonBackend\n"; PyRun_SimpleString(prepareCommand); PyObject* compile = Py_CompileString(command.toStdString().c_str(), filePath.toStdString().c_str(), Py_single_input); // There are two reasons for the error: // 1) This code is not single expression, so we can't compile this with flag Py_single_input // 2) There are errors in the code if (PyErr_Occurred()) { PyErr_Clear(); // Try to recompile code as sequence of expressions compile = Py_CompileString(command.toStdString().c_str(), filePath.toStdString().c_str(), Py_file_input); if (PyErr_Occurred()) { // We now know, that we have a syntax error, so print the traceback and exit PyErr_PrintEx(0); return; } } #if PY_MAJOR_VERSION == 3 PyEval_EvalCode(compile, py_dict, py_dict); #elif PY_MAJOR_VERSION == 2 PyEval_EvalCode((PyCodeObject*)compile, py_dict, py_dict); #else #warning Unknown Python version #endif if (PyErr_Occurred()) PyErr_PrintEx(0); } QString PythonServer::getError() const { PyObject *errorPython = PyObject_GetAttrString(m_pModule, "errorPythonBackend"); PyObject *error = PyObject_GetAttrString(errorPython, "value"); return pyObjectToQString(error); } QString PythonServer::getOutput() const { PyObject *outputPython = PyObject_GetAttrString(m_pModule, "outputPythonBackend"); PyObject *output = PyObject_GetAttrString(outputPython, "value"); return pyObjectToQString(output); } void PythonServer::setFilePath(const QString& path) { this->filePath = path; PyRun_SimpleString(("__file__ = '"+path.toStdString()+"'").c_str()); } diff --git a/src/backends/python2/python2server/main.cpp b/src/backends/python2/python2server/main.cpp index 92cca0c1..82945d16 100644 --- a/src/backends/python2/python2server/main.cpp +++ b/src/backends/python2/python2server/main.cpp @@ -1,54 +1,54 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2015 Minh Ngo */ #include #include #include #include #include #include "../../python/pythonserver.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); if (!QDBusConnection::sessionBus().isConnected()) { qDebug() << "Can't connect to the D-Bus session bus.\n" "To start it, run: eval `dbus-launch --auto-syntax`"; return 1; } - const QString& serviceName = QString::fromLatin1("org.kde.Cantor.Python2-%1").arg(app.applicationPid()); + const QString& serviceName = QStringLiteral("org.kde.Cantor.Python2-%1").arg(app.applicationPid()); if (!QDBusConnection::sessionBus().registerService(serviceName)) { qDebug() << QDBusConnection::sessionBus().lastError().message(); return 2; } PythonServer server; - QDBusConnection::sessionBus().registerObject(QString::fromLatin1("/"), &server, QDBusConnection::ExportAllSlots); + QDBusConnection::sessionBus().registerObject(QStringLiteral("/"), &server, QDBusConnection::ExportAllSlots); QTextStream(stdout) << "ready" << endl; return app.exec(); } diff --git a/src/backends/python3/python3server/main.cpp b/src/backends/python3/python3server/main.cpp index d0d20c3b..f396cd0f 100644 --- a/src/backends/python3/python3server/main.cpp +++ b/src/backends/python3/python3server/main.cpp @@ -1,54 +1,54 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2015 Minh Ngo */ #include #include #include #include #include #include "../../python/pythonserver.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); if (!QDBusConnection::sessionBus().isConnected()) { qDebug() << "Can't connect to the D-Bus session bus.\n" "To start it, run: eval `dbus-launch --auto-syntax`"; return 1; } - const QString& serviceName = QString::fromLatin1("org.kde.Cantor.Python3-%1").arg(app.applicationPid()); + const QString& serviceName = QStringLiteral("org.kde.Cantor.Python3-%1").arg(app.applicationPid()); if (!QDBusConnection::sessionBus().registerService(serviceName)) { qDebug() << QDBusConnection::sessionBus().lastError().message(); return 2; } PythonServer server; - QDBusConnection::sessionBus().registerObject(QString::fromLatin1("/"), &server, QDBusConnection::ExportAllSlots); + QDBusConnection::sessionBus().registerObject(QStringLiteral("/"), &server, QDBusConnection::ExportAllSlots); QTextStream(stdout) << "ready" << endl; return app.exec(); } diff --git a/src/lib/animationresult.cpp b/src/lib/animationresult.cpp index 9a5fd379..deb23bb3 100644 --- a/src/lib/animationresult.cpp +++ b/src/lib/animationresult.cpp @@ -1,105 +1,105 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "animationresult.h" using namespace Cantor; #include #include #include #include #include #include #include class Cantor::AnimationResultPrivate { public: AnimationResultPrivate() = default; QUrl url; QMovie* movie; QString alt; }; AnimationResult::AnimationResult(const QUrl &url, const QString& alt ) : d(new AnimationResultPrivate) { d->url=url; d->alt=alt; d->movie=new QMovie(); d->movie->setFileName(url.toLocalFile()); } AnimationResult::~AnimationResult() { delete d->movie; delete d; } QString AnimationResult::toHtml() { - return QString::fromLatin1("\"%2\"/").arg(d->url.toLocalFile(), d->alt); + return QStringLiteral("\"%2\"/").arg(d->url.toLocalFile(), d->alt); } QVariant AnimationResult::data() { return QVariant::fromValue(static_cast(d->movie)); } QUrl AnimationResult::url() { return d->url; } int AnimationResult::type() { return AnimationResult::Type; } QString AnimationResult::mimeType() { QMimeDatabase db; QMimeType type = db.mimeTypeForUrl(d->url); return type.name(); } QDomElement AnimationResult::toXml(QDomDocument& doc) { qDebug()<<"saving imageresult "<url.fileName()); + QDomElement e=doc.createElement(QStringLiteral("Result")); + e.setAttribute(QStringLiteral("type"), QStringLiteral("animation")); + e.setAttribute(QStringLiteral("filename"), d->url.fileName()); qDebug()<<"done"; return e; } void AnimationResult::saveAdditionalData(KZip* archive) { archive->addLocalFile(d->url.toLocalFile(), d->url.fileName()); } void AnimationResult::save(const QString& filename) { //just copy over the file.. KIO::file_copy(d->url, QUrl::fromLocalFile(filename), -1, KIO::HideProgressInfo); } diff --git a/src/lib/assistant.cpp b/src/lib/assistant.cpp index ee7f3873..4a9a6f6d 100644 --- a/src/lib/assistant.cpp +++ b/src/lib/assistant.cpp @@ -1,75 +1,75 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "assistant.h" using namespace Cantor; class Cantor::AssistantPrivate { public: QString name; QString icon; QStringList requiredExtensions; Backend* backend; }; Assistant::Assistant(QObject* parent) : QObject(parent), KXMLGUIClient(dynamic_cast(parent)), d(new AssistantPrivate) { } Assistant::~Assistant() { delete d; } void Assistant::setBackend(Cantor::Backend* backend) { d->backend=backend; } -void Assistant::setPluginInfo(KPluginMetaData info) +void Assistant::setPluginInfo(const KPluginMetaData &info) { d->name=info.name(); d->icon=info.iconName(); - d->requiredExtensions=info.value(QLatin1String("RequiredExtensions")).split(QLatin1Char(',')); + d->requiredExtensions=info.value(QStringLiteral("RequiredExtensions")).split(QLatin1Char(',')); } QStringList Assistant::requiredExtensions() { return d->requiredExtensions; } QString Assistant::icon() { return d->icon; } QString Assistant::name() { return d->name; } Backend* Assistant::backend() { return d->backend; } diff --git a/src/lib/assistant.h b/src/lib/assistant.h index 95e0415b..d4970273 100644 --- a/src/lib/assistant.h +++ b/src/lib/assistant.h @@ -1,115 +1,115 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #ifndef _ASSISTANT_H #define _ASSISTANT_H #include #include #include #include "cantor_export.h" namespace Cantor { class Backend; class AssistantPrivate; /** * An Assistant is a dialog for simplifying common tasks, like integrating, solving, or running scripts * To perform their task, they rely on one or more Extensions, to translate to the backends specific syntax. * @see Extension */ class CANTOR_EXPORT Assistant : public QObject, public KXMLGUIClient { Q_OBJECT public: /** * Create a new assistant * @param parent the parent Object @see QObject **/ explicit Assistant( QObject* parent ); /** * Destructor */ ~Assistant() override; /** * Sets the backend, this Assistant operates on * @param backend the new backend */ void setBackend(Backend* backend); /** * Sets the properties of this Assistant * according to KPluginMetaData * @param info KPluginMetaData */ - void setPluginInfo(KPluginMetaData info); + void setPluginInfo(const KPluginMetaData &info); /** * Returns a list of all extensions, the current backend * must provide to make this Assistant work. If it doesn't * this Assistant won't be shown in the Menu * @return list of required extensions */ QStringList requiredExtensions(); /** * shows the assistants dialog or gui it offers, and returns a list of commands * to be run, to achieve the desired effect * @param parent the parent widget, each created Widget should use */ virtual QStringList run(QWidget* parent) = 0; /** * initialize the needed KActions/integrate into the menu bars */ virtual void initActions() = 0; /** * Returns the icon, this Assistant is using * @return icon, this Assistant is using */ QString icon(); /** * Returns the name of the assistant * @return name of the assistant */ QString name(); /** * Returns the backend, this assistant operates on * @return backend, this assistant operates on */ Backend* backend(); Q_SIGNALS: /** * signal emitted, if the user has requested this Assistant to run * e.g. by clicking on its action in the menu */ void requested(); private: AssistantPrivate* d; }; } #endif /* _ASSISTANT_H */ diff --git a/src/lib/completionobject.cpp b/src/lib/completionobject.cpp index 0840677d..062433c0 100644 --- a/src/lib/completionobject.cpp +++ b/src/lib/completionobject.cpp @@ -1,292 +1,292 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "completionobject.h" using namespace Cantor; #include #include #include #include "session.h" class Cantor::CompletionObjectPrivate { public: QStringList completions; QString line; QString command; QString identifier; QString completion; int position; Session* session; bool parenCompletion; }; CompletionObject::CompletionObject(Session* session) : d(new CompletionObjectPrivate) { setParent(session); d->position = -1; d->session=session; connect(this, &CompletionObject::fetchingDone, this, &CompletionObject::findCompletion); connect(this, &CompletionObject::fetchingTypeDone, this, &CompletionObject::completeLineWithType); setCompletionMode(KCompletion::CompletionShell); } CompletionObject::~CompletionObject() { delete d; } QString CompletionObject::command() const { return d->command; } Session* CompletionObject::session() const { return d->session; } QStringList CompletionObject::completions() const { return d->completions; } QString CompletionObject::identifier() const { return d->identifier; } QString CompletionObject::completion() const { return d->completion; } void CompletionObject::setLine(const QString& line, int index) { d->parenCompletion = false; d->line = line; if (index < 0) index = line.length(); if (index > 1 && line[index-1] == QLatin1Char('(')) { --index; // move before the parenthesis d->parenCompletion = true; // but remember it was there } int cmd_index = locateIdentifier(line, index-1); if (cmd_index < 0) cmd_index = index; d->position=cmd_index; d->command=line.mid(cmd_index, index-cmd_index); //start a delayed fetch - QTimer::singleShot(0, this, SLOT(fetchCompletions())); + QTimer::singleShot(0, this, &CompletionObject::fetchCompletions); } void CompletionObject::updateLine(const QString& line, int index) { d->line = line; if (index < 0) index = line.length(); int cmd_index = locateIdentifier(line, index-1); if (cmd_index < 0) cmd_index = index; d->command=line.mid(cmd_index, index-cmd_index); // start a delayed fetch // For some backends this is a lot of unnecessary work... - QTimer::singleShot(0, this, SLOT(fetchCompletions())); + QTimer::singleShot(0, this, &CompletionObject::fetchCompletions); } void CompletionObject::completeLine(const QString& comp, CompletionObject::LineCompletionMode mode) { d->identifier = comp; if (comp.isEmpty()) { int index = d->position + d->command.length(); emit lineDone(d->line, index); } else if (mode == PreliminaryCompletion) { completeUnknownLine(); } else /* mode == FinalCompletion */ { - QTimer::singleShot(0, this, SLOT(fetchIdentifierType())); + QTimer::singleShot(0, this, &CompletionObject::fetchIdentifierType); } } void CompletionObject::fetchIdentifierType() { emit fetchingTypeDone(UnknownType); } void CompletionObject::setCompletions(const QStringList& completions) { d->completions=completions; this->setItems(completions); } void CompletionObject::setCommand(const QString& cmd) { d->command=cmd; } int CompletionObject::locateIdentifier(const QString& cmd, int index) const { if (index < 0) return -1; int i; for (i=index; i>=0 && mayIdentifierContain(cmd[i]); --i) {} if (i==index || !mayIdentifierBeginWith(cmd[i+1])) return -1; return i+1; } bool CompletionObject::mayIdentifierContain(QChar c) const { return c.isLetter() || c.isDigit() || c == QLatin1Char('_'); } bool CompletionObject::mayIdentifierBeginWith(QChar c) const { return c.isLetter() || c == QLatin1Char('_'); } void CompletionObject::findCompletion() { if (d->parenCompletion) { disconnect(this, SIGNAL(fetchingTypeDone(IdentifierType)), nullptr, nullptr); connect(this, &CompletionObject::fetchingTypeDone, this, &CompletionObject::handleParenCompletionWithType); d->identifier = d->command; fetchIdentifierType(); return; } d->completion = makeCompletion(command()); emit done(); } void CompletionObject::handleParenCompletionWithType(IdentifierType type) { disconnect(this, SIGNAL(fetchingTypeDone(IdentifierType)), nullptr, nullptr); connect(this, &CompletionObject::fetchingTypeDone, this, &CompletionObject::completeLineWithType); if (type == FunctionWithArguments || type == FunctionWithoutArguments) { d->completion = d->command; emit done(); } } void CompletionObject::completeLineWithType(IdentifierType type) { switch(type) { case VariableType: completeVariableLine(); break; case FunctionWithArguments: case FunctionWithoutArguments: completeFunctionLine(type); break; case KeywordType: completeKeywordLine(); break; case UnknownType: completeUnknownLine(); break; } } void CompletionObject::completeFunctionLine(IdentifierType type) { QString newline; int newindex; QString func = d->identifier; int after_command = d->position + d->command.length(); QString part1 = d->line.left(d->position) + func; int index = d->position + func.length() + 1; if (after_command < d->line.length() && d->line.at(after_command) == QLatin1Char('(')) { QString part2 = d->line.mid(after_command+1); int i; // search for next non-space position for (i = after_command+1; i < d->line.length() && d->line.at(i).isSpace(); ++i) {} if (type == FunctionWithArguments) { if (i < d->line.length()) { newline = part1+QLatin1Char('(')+part2; newindex = index; } else { newline = part1+QLatin1String("()")+part2; newindex = index; } } else /*type == FunctionWithoutArguments*/ { if (i < d->line.length() && d->line.at(i) == QLatin1Char(')')) { newline = part1+QLatin1Char('(')+part2; newindex = index+i-after_command; } else { newline = part1+QLatin1String("()")+part2; newindex = index+1; } } } else { QString part2 = d->line.mid(after_command); if (type == FunctionWithArguments) { newline = part1+QLatin1String("()")+part2; newindex = index; } else /*type == FunctionWithoutArguments*/ { newline = part1+QLatin1String("()")+part2; newindex = index+1; } } emit lineDone(newline, newindex); } void CompletionObject::completeKeywordLine() { QString keyword = d->identifier; int after_command = d->position + d->command.length(); int newindex = d->position + keyword.length() + 1; QString part1 = d->line.left(d->position) + keyword; QString part2 = d->line.mid(after_command); if (after_command < d->line.length() && d->line.at(after_command) == QLatin1Char(' ')) emit lineDone(part1+part2, newindex); else emit lineDone(part1+QLatin1Char(' ')+part2, newindex); } void CompletionObject::completeVariableLine() { QString var = d->identifier; int after_command = d->position + d->command.length(); QString newline = d->line.left(d->position) + var + d->line.mid(after_command); int newindex = d->position + var.length(); emit lineDone(newline, newindex); } void CompletionObject::completeUnknownLine() { // identifiers of unknown type are completed like variables completeVariableLine(); } diff --git a/src/lib/completionobject.h b/src/lib/completionobject.h index cda6f0c8..cd8dfe50 100644 --- a/src/lib/completionobject.h +++ b/src/lib/completionobject.h @@ -1,225 +1,225 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #ifndef _COMPLETIONOBJECT_H #define _COMPLETIONOBJECT_H #include #include "cantor_export.h" namespace Cantor { class CompletionObjectPrivate; class Session; /** * This Object is used to provide a Tab Completion, in an asynchronous way. * Each backend, supporting tab completion, needs to provide their own * CompletionObject, that reimplements the fetching of the completions * and emits done() as soon as the completions are available * * @author Alexander Rieder */ class CANTOR_EXPORT CompletionObject : public KCompletion { Q_OBJECT public: /** * Constructor * @param parent the session, this object belongs to */ explicit CompletionObject(Session* parent); ///Destructor ~CompletionObject() override; enum LineCompletionMode { PreliminaryCompletion, ///< Only insert the completion FinalCompletion ///< also add () for functions, etc }; /** * Returns a list of completions * @return a list of completions */ QStringList completions() const; /** * Returns the last completion * @return the last completion */ QString completion() const; /** * returns the command, this completion is for * @return the command, this completion is for */ QString command() const; /** * returns the session, this object belongs to * @return the session, this object belongs to */ Session* session() const; /** * Sets the line and cursor index at which a completion should be found * This triggers an asynchronous fetching of completions, * which emits done() when done. * @param line the line that is to be completed * @param index the cursor position in line */ void setLine(const QString& line, int index); /** * Takes the changed line and updates the command accordingly. * This triggers an asynchronous fetching of completions, * which emits done() when done. * @param line the line that is to be completed * @param index the cursor position in line */ void updateLine(const QString& line, int index); /** * Takes a completion and a completion mode and triggers and calculates * the new line with this completion. If the completion mode is * FinalCompletion some postprocessing is done asynchronously. * Emits lineDone when finished. * @param comp the completion that's to be processed * @param mode the mode of completion. Can be PreliminaryCompletion * (insert only) or FinalCompletion (also add () for functions, etc.) */ void completeLine(const QString& comp, LineCompletionMode mode); protected: enum IdentifierType { VariableType, ///< a variable FunctionWithArguments, ///< a function that takes arguments FunctionType = FunctionWithArguments, ///< an alias for function with arguments FunctionWithoutArguments, ///< a function that takes no arguments KeywordType, ///< a keyword UnknownType ///< no identifier type was found }; /** * returns the identifier for fetchIdentifierType * @return the identifier for fetchIdentifierType */ QString identifier() const; /** * Sets the completions * @param completions list of possible completions */ void setCompletions(const QStringList& completions); /** * sets the command/command-part * @param cmd the command/command-part */ void setCommand(const QString& cmd); /** * Find an identifier in cmd that ends at index * @param cmd the command * @param index the index to look at */ virtual int locateIdentifier(const QString& cmd, int index) const; /** * return true if c may be used in identifier names * @param c the character */ virtual bool mayIdentifierContain(QChar c) const; /** * return true if identifier names can begin with c * @param c the character */ virtual bool mayIdentifierBeginWith(QChar c) const; /** * Completes line with function identifier and emits lineDone with the * completed line. Helper function for completeLine. * @param type whether the function takes arguments, default: FunctionWithArguments */ void completeFunctionLine(IdentifierType type = FunctionWithArguments); /** * Completes line with keyword identifier and emits lineDone with the * completed line. Helper function for completeLine. */ void completeKeywordLine(); /** * Completes line with variable identifier and emits lineDone with the * completed line. Helper function for completeLine. */ void completeVariableLine(); /** * Completes line with identifier of unknown type and emits lineDone with * the completed line. Helper function for completeLine. */ void completeUnknownLine(); protected Q_SLOTS: /** * This function should be reimplemented to start the actual fetching * of the completions. It can be asynchronous. * Remember to emit fetchingDone, if the fetching is complete */ virtual void fetchCompletions() = 0; /** * Fetch the identifier type of d->identifier; reimplemented in * the backends. Emit fetchingTypeDone when done. */ virtual void fetchIdentifierType(); /** * Find the completion. To be called when fetching is done. * Emits done() when done. */ void findCompletion(); /** * Calls the appropriate complete*Line based on type * @param type the identifier type found in line() */ void completeLineWithType(Cantor::CompletionObject::IdentifierType type); /** * Handle a completion request after a opening parenthesis. * @param type the type of the identifier before the parenthesis */ void handleParenCompletionWithType(Cantor::CompletionObject::IdentifierType type); Q_SIGNALS: /** * indicates that the fetching of completions is done */ void fetchingDone(); /** * indicates that the type of identifier() was found and passes the * type as an argument * @param type the identifier type */ void fetchingTypeDone(Cantor::CompletionObject::IdentifierType type); /** * indicates that the possible completions and a common completion string * have been found */ void done(); /** * emitted when the line completion is done, passes the new line and * the cursor index * @param line the new line * @param index the new cursor index */ - void lineDone(QString line, int index); + void lineDone(const QString &line, int index); private: CompletionObjectPrivate* d; }; } #endif /* _COMPLETIONOBJECT_H */ diff --git a/src/lib/defaulthighlighter.cpp b/src/lib/defaulthighlighter.cpp index ee09dab2..5792cd26 100644 --- a/src/lib/defaulthighlighter.cpp +++ b/src/lib/defaulthighlighter.cpp @@ -1,460 +1,460 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder Copyright (C) 2006 David Saxton */ #include "defaulthighlighter.h" #include #include #include #include #include #include #include #include using namespace Cantor; struct HighlightingRule { QRegExp regExp; QTextCharFormat format; }; bool operator==(const HighlightingRule& rule1, const HighlightingRule& rule2) { return rule1.regExp == rule2.regExp; } struct PairOpener { PairOpener() : position(-1), type(-1) { } PairOpener(int p, int t) : position(p), type(t) { } int position; int type; }; class Cantor::DefaultHighlighterPrivate { public: QTextCursor cursor; //Character formats to use for the highlighting QTextCharFormat functionFormat; QTextCharFormat variableFormat; QTextCharFormat objectFormat; QTextCharFormat keywordFormat; QTextCharFormat numberFormat; QTextCharFormat operatorFormat; QTextCharFormat errorFormat; QTextCharFormat commentFormat; QTextCharFormat stringFormat; QTextCharFormat matchingPairFormat; QTextCharFormat mismatchingPairFormat; int lastBlockNumber; int lastPosition; bool suppressRuleChangedSignal; // each two consecutive items build a pair QList pairs; QList regExpRules; QHash wordRules; }; DefaultHighlighter::DefaultHighlighter(QObject* parent) : QSyntaxHighlighter(parent), d(new DefaultHighlighterPrivate) { d->cursor = QTextCursor(); d->lastBlockNumber=-1; d->lastPosition=-1; d->suppressRuleChangedSignal = false; addPair(QLatin1Char('('), QLatin1Char(')')); addPair(QLatin1Char('['), QLatin1Char(']')); addPair(QLatin1Char('{'), QLatin1Char('}')); updateFormats(); - connect(qApp, SIGNAL(paletteChanged(QPalette)), - this, SLOT(updateFormats())); + connect(qApp, &QGuiApplication::paletteChanged, + this, &DefaultHighlighter::updateFormats); } DefaultHighlighter::~DefaultHighlighter() { delete d; } void DefaultHighlighter::setTextItem(QGraphicsTextItem* item) { d->cursor = item->textCursor(); setDocument(item->document()); // make sure every item is connected only once item->disconnect(this, SLOT(positionChanged(QTextCursor))); // QGraphicsTextItem has no signal cursorPositionChanged, but item really // is a WorksheetTextItem connect(item, SIGNAL(cursorPositionChanged(QTextCursor)), this, SLOT(positionChanged(QTextCursor))); d->lastBlockNumber = -1; d->lastPosition = -1; } bool DefaultHighlighter::skipHighlighting(const QString& text) { return text.isEmpty(); } void DefaultHighlighter::highlightBlock(const QString& text) { //qDebug() << text; const QTextCursor& cursor = d->cursor; d->lastBlockNumber = cursor.blockNumber(); if (skipHighlighting(text)) return; highlightPairs(text); highlightWords(text); highlightRegExps(text); } void DefaultHighlighter::addPair(QChar openSymbol, QChar closeSymbol) { Q_ASSERT(!d->pairs.contains(openSymbol)); Q_ASSERT(!d->pairs.contains(closeSymbol)); d->pairs << openSymbol << closeSymbol; } void DefaultHighlighter::highlightPairs(const QString& text) { //qDebug() << text; const QTextCursor& cursor = d->cursor; int cursorPos = -1; if (cursor.blockNumber() == currentBlock().blockNumber() ) { cursorPos = cursor.position() - currentBlock().position(); // when text changes, this will be called before the positionChanged signal // gets emitted. Hence update the position so we don't highlight twice d->lastPosition = cursor.position(); } QStack opened; for (int i = 0; i < text.size(); ++i) { int idx = d->pairs.indexOf(text[i]); if (idx == -1) continue; if (idx % 2 == 0) { //opener of a pair opened.push(PairOpener(i, idx)); } else if (opened.isEmpty()) { //closer with no previous opener setFormat(i, 1, errorFormat()); } else if (opened.top().type == idx - 1) { //closer with matched opener int openPos = opened.pop().position; if (cursorPos != -1 && (openPos == cursorPos || openPos == cursorPos - 1 || i == cursorPos || i == cursorPos - 1)) { setFormat(openPos, 1, matchingPairFormat()); setFormat(i, 1, matchingPairFormat()); } } else { //closer with mismatching opener int openPos = opened.pop().position; setFormat(openPos, 1, mismatchingPairFormat()); setFormat(i, 1, mismatchingPairFormat()); } } // handled unterminated pairs while (!opened.isEmpty()) { int position = opened.pop().position; setFormat(position, 1, errorFormat()); } } void DefaultHighlighter::highlightWords(const QString& text) { //qDebug() << "DefaultHighlighter::highlightWords"; const QStringList& words = text.split(QRegExp(QLatin1String("\\b")), QString::SkipEmptyParts); int count; int pos = 0; const int n = words.size(); for (int i = 0; i < n; ++i) { count = words[i].size(); QString word = words[i]; //kind of a HACK: //look at previous words, if they end with allowed characters, //prepend them to the current word. This allows for example //to highlight words that start with a "Non-word"-character //e.g. %pi in the scilab backend. //qDebug() << "nonSeparatingCharacters().isNull(): " << nonSeparatingCharacters().isNull(); if(!nonSeparatingCharacters().isNull()) { for(int j = i - 1; j >= 0; j--) { //qDebug() << "j: " << j << "w: " << words[j]; const QString& w = words[j]; - const QString exp = QString::fromLatin1("(%1)*$").arg(nonSeparatingCharacters()); + const QString exp = QStringLiteral("(%1)*$").arg(nonSeparatingCharacters()); //qDebug() << "exp: " << exp; int idx = w.indexOf(QRegExp(exp)); const QString& s = w.mid(idx); //qDebug() << "s: " << s; if(s.size() > 0) { pos -= s.size(); count += s.size(); word = s + word; } else{ break; } } } word = word.trimmed(); //qDebug() << "highlighing: " << word; if (d->wordRules.contains(word)) { setFormat(pos, count, d->wordRules[word]); } pos += count; } } void DefaultHighlighter::highlightRegExps(const QString& text) { foreach (const HighlightingRule& rule, d->regExpRules) { int index = rule.regExp.indexIn(text); while (index >= 0) { int length = rule.regExp.matchedLength(); setFormat(index, length, rule.format); index = rule.regExp.indexIn(text, index + length); } } } QTextCharFormat DefaultHighlighter::functionFormat() const { return d->functionFormat; } QTextCharFormat DefaultHighlighter::variableFormat() const { return d->variableFormat; } QTextCharFormat DefaultHighlighter::objectFormat() const { return d->objectFormat; } QTextCharFormat DefaultHighlighter::keywordFormat() const { return d->keywordFormat; } QTextCharFormat DefaultHighlighter::numberFormat() const { return d->numberFormat; } QTextCharFormat DefaultHighlighter::operatorFormat() const { return d->operatorFormat; } QTextCharFormat DefaultHighlighter::errorFormat() const { return d->errorFormat; } QTextCharFormat DefaultHighlighter::commentFormat() const { return d->commentFormat; } QTextCharFormat DefaultHighlighter::stringFormat() const { return d->stringFormat; } QTextCharFormat DefaultHighlighter::matchingPairFormat() const { return d->matchingPairFormat; } QTextCharFormat DefaultHighlighter::mismatchingPairFormat() const { return d->mismatchingPairFormat; } void DefaultHighlighter::updateFormats() { //initialize char-formats KColorScheme scheme(QPalette::Active); d->functionFormat.setForeground(scheme.foreground(KColorScheme::LinkText)); d->functionFormat.setFontWeight(QFont::DemiBold); d->variableFormat.setForeground(scheme.foreground(KColorScheme::ActiveText)); d->objectFormat.setForeground(scheme.foreground(KColorScheme::NormalText)); d->objectFormat.setFontWeight(QFont::Bold); d->keywordFormat.setForeground(scheme.foreground(KColorScheme::NeutralText)); d->keywordFormat.setFontWeight(QFont::Bold); d->numberFormat.setForeground(scheme.foreground(KColorScheme::NeutralText)); d->operatorFormat.setForeground(scheme.foreground(KColorScheme::NormalText)); d->operatorFormat.setFontWeight(QFont::Bold); d->errorFormat.setForeground(scheme.foreground(KColorScheme::NormalText)); d->errorFormat.setUnderlineColor(scheme.foreground(KColorScheme::NegativeText).color()); d->errorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); d->commentFormat.setForeground(scheme.foreground(KColorScheme::InactiveText)); d->stringFormat.setForeground(scheme.foreground(KColorScheme::PositiveText)); d->matchingPairFormat.setForeground(scheme.foreground(KColorScheme::NeutralText)); d->matchingPairFormat.setBackground(scheme.background(KColorScheme::NeutralBackground)); d->mismatchingPairFormat.setForeground(scheme.foreground(KColorScheme::NegativeText)); d->mismatchingPairFormat.setBackground(scheme.background(KColorScheme::NegativeBackground)); } void DefaultHighlighter::positionChanged(const QTextCursor& cursor) { if (!cursor.isNull() && cursor.document() != document()) // A new item notified us, but we did not yet change our document. // We are waiting for that to happen. return; d->cursor = cursor; if ( (cursor.isNull() || cursor.blockNumber() != d->lastBlockNumber) && d->lastBlockNumber >= 0 ) { // remove highlight from last focused block rehighlightBlock(document()->findBlockByNumber(d->lastBlockNumber)); } if (cursor.isNull()) { d->lastBlockNumber = -1; d->lastPosition = -1; return; } d->lastBlockNumber = cursor.blockNumber(); if ( d->lastPosition == cursor.position() ) { return; } rehighlightBlock(cursor.block()); d->lastPosition = cursor.position(); } void DefaultHighlighter::addRule(const QString& word, const QTextCharFormat& format) { d->wordRules[word] = format; if (!d->suppressRuleChangedSignal) emit rulesChanged(); } void DefaultHighlighter::addRule(const QRegExp& regexp, const QTextCharFormat& format) { HighlightingRule rule = { regexp, format }; d->regExpRules.removeAll(rule); d->regExpRules.append(rule); if (!d->suppressRuleChangedSignal) emit rulesChanged(); } void DefaultHighlighter::removeRule(const QString& word) { d->wordRules.remove(word); if (!d->suppressRuleChangedSignal) emit rulesChanged(); } void DefaultHighlighter::removeRule(const QRegExp& regexp) { HighlightingRule rule = { regexp, QTextCharFormat() }; d->regExpRules.removeAll(rule); if (!d->suppressRuleChangedSignal) emit rulesChanged(); } void DefaultHighlighter::addRules(const QStringList& conditions, const QTextCharFormat& format) { typename QStringList::const_iterator i = conditions.constBegin(); typename QStringList::const_iterator end = conditions.constEnd(); d->suppressRuleChangedSignal = true; for (;i != end; ++i) { addRule(*i, format); } d->suppressRuleChangedSignal = false; emit rulesChanged(); } void DefaultHighlighter::addFunctions(const QStringList& functions) { addRules(functions, functionFormat()); } void DefaultHighlighter::addKeywords(const QStringList& keywords) { addRules(keywords, keywordFormat()); } void DefaultHighlighter::addVariables(const QStringList& variables) { addRules(variables, variableFormat()); } void DefaultHighlighter::removeRules(const QStringList& conditions) { typename QStringList::const_iterator i = conditions.constBegin(); typename QStringList::const_iterator end = conditions.constEnd(); d->suppressRuleChangedSignal = true; for (;i != end; ++i) { removeRule(*i); } d->suppressRuleChangedSignal = false; emit rulesChanged(); } QString DefaultHighlighter::nonSeparatingCharacters() const { return QString(); } diff --git a/src/lib/defaultvariablemodel.cpp b/src/lib/defaultvariablemodel.cpp index 29c55bfe..e8837abb 100644 --- a/src/lib/defaultvariablemodel.cpp +++ b/src/lib/defaultvariablemodel.cpp @@ -1,193 +1,193 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2010 Miha Čančula */ #include "defaultvariablemodel.h" #include #include #include "extension.h" #include "backend.h" namespace Cantor { class DefaultVariableModelPrivate { public: QList variables; Session* session; VariableManagementExtension* extension; }; DefaultVariableModel::DefaultVariableModel(Session* session): QAbstractTableModel(session), d_ptr(new DefaultVariableModelPrivate) { Q_D(DefaultVariableModel); d->session = session; if (session) { - d->extension = dynamic_cast(session->backend()->extension(QLatin1String("VariableManagementExtension"))); + d->extension = dynamic_cast(session->backend()->extension(QStringLiteral("VariableManagementExtension"))); } qDebug() << d->session << d->extension; } int DefaultVariableModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return ColumnCount; } int DefaultVariableModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) { return 0; } else { Q_D(const DefaultVariableModel); return d->variables.size(); } } QVariant DefaultVariableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(role==Qt::DisplayRole && orientation==Qt::Horizontal) { switch(section) { case NameColumn: return i18nc("@title:column", "Name"); case ValueColumn: return i18nc("@title:column", "Value"); break; } } return QVariant(); } Qt::ItemFlags DefaultVariableModel::flags(const QModelIndex& index) const { return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } QVariant DefaultVariableModel::data(const QModelIndex& index, int role) const { if (role != Qt::DisplayRole || !index.isValid()) { return QVariant(); } Q_D(const DefaultVariableModel); switch (index.column()) { case NameColumn: return QVariant(d->variables[index.row()].name); case ValueColumn: return QVariant(d->variables[index.row()].value); default: return QVariant(); } } bool DefaultVariableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if(role!=Qt::EditRole || !value.isValid() || !index.isValid()) { return false; } Q_D(const DefaultVariableModel); if(index.column() == ValueColumn) { // Changing values QString name = data(index.sibling(index.row(), NameColumn)).toString(); d->session->evaluateExpression(d->extension->setValue(name, value.toString()), Expression::DeleteOnFinish); return true; } else if(index.column() == NameColumn) { // Renaming => copy it, then delete the old one QString oldName = data(index).toString(); QString variableValue = data(index.sibling(index.row(), ValueColumn)).toString(); d->session->evaluateExpression(d->extension->addVariable(value.toString(), variableValue), Expression::DeleteOnFinish); d->session->evaluateExpression(d->extension->removeVariable(oldName), Expression::DeleteOnFinish); return true; } return false; } void DefaultVariableModel::addVariable(const QString& name, const QString& value) { Variable v; v.name = name; v.value = value; addVariable(v); } void DefaultVariableModel::addVariable(const Cantor::DefaultVariableModel::Variable& variable) { Q_D(DefaultVariableModel); if ( d->variables.contains(variable) ) { removeVariable(variable); } beginInsertRows(QModelIndex(), d->variables.size(), d->variables.size()); d->variables.append(variable); endInsertRows(); } void DefaultVariableModel::removeVariable(const QString& name) { Variable v; v.name = name; removeVariable(v); } void DefaultVariableModel::removeVariable(const Cantor::DefaultVariableModel::Variable& variable) { Q_D(DefaultVariableModel); int row = d->variables.indexOf(variable); if(row==-1) return; beginRemoveRows(QModelIndex(), row, row); d->variables.removeAt(row); endRemoveRows(); } void DefaultVariableModel::clearVariables() { Q_D(DefaultVariableModel); beginResetModel(); d->variables.clear(); endResetModel(); } Session* DefaultVariableModel::session() const { Q_D(const DefaultVariableModel); return d->session; } bool operator==(const Cantor::DefaultVariableModel::Variable& one, const Cantor::DefaultVariableModel::Variable& other) { return one.name == other.name; } } diff --git a/src/lib/epsresult.cpp b/src/lib/epsresult.cpp index cf5ae576..32148c21 100644 --- a/src/lib/epsresult.cpp +++ b/src/lib/epsresult.cpp @@ -1,99 +1,99 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "epsresult.h" using namespace Cantor; #include #include #include #include class Cantor::EpsResultPrivate{ public: QUrl url; }; EpsResult::EpsResult(const QUrl& url) : d(new EpsResultPrivate) { d->url=url; #ifndef WITH_EPS qDebug()<<"Creating an EpsResult in an environment compiled without EPS support!"; #endif } EpsResult::~EpsResult() { delete d; } QString EpsResult::toHtml() { - return QString::fromLatin1("").arg(d->url.url()); + return QStringLiteral("").arg(d->url.url()); } QString EpsResult::toLatex() { - return QString::fromLatin1(" \\begin{center} \n \\includegraphics[width=12cm]{%1}\n \\end{center}").arg(d->url.fileName()); + return QStringLiteral(" \\begin{center} \n \\includegraphics[width=12cm]{%1}\n \\end{center}").arg(d->url.fileName()); } QVariant EpsResult::data() { return QVariant(d->url); } QUrl EpsResult::url() { return d->url; } int EpsResult::type() { return EpsResult::Type; } QString EpsResult::mimeType() { - return QLatin1String("image/x-eps"); + return QStringLiteral("image/x-eps"); } QDomElement EpsResult::toXml(QDomDocument& doc) { qDebug()<<"saving imageresult "<url.fileName()); + QDomElement e=doc.createElement(QStringLiteral("Result")); + e.setAttribute(QStringLiteral("type"), QStringLiteral("image")); + e.setAttribute(QStringLiteral("filename"), d->url.fileName()); qDebug()<<"done"; return e; } void EpsResult::saveAdditionalData(KZip* archive) { archive->addLocalFile(d->url.toLocalFile(), d->url.fileName()); } void EpsResult::save(const QString& filename) { //just copy over the eps file.. KIO::file_copy(d->url, QUrl::fromLocalFile(filename), -1, KIO::HideProgressInfo); } diff --git a/src/lib/extension.cpp b/src/lib/extension.cpp index 90593739..7b943a43 100644 --- a/src/lib/extension.cpp +++ b/src/lib/extension.cpp @@ -1,149 +1,149 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "extension.h" using namespace Cantor; #include #define EXTENSION_CONSTRUCTORS(name) name::name(QObject* parent) : Extension(QLatin1String(#name),parent) {} \ name::~name() {} Extension::Extension(const QString& name, QObject* parent) : QObject(parent) { setObjectName(name); } EXTENSION_CONSTRUCTORS(HistoryExtension) EXTENSION_CONSTRUCTORS(ScriptExtension) EXTENSION_CONSTRUCTORS(CASExtension) EXTENSION_CONSTRUCTORS(CalculusExtension) EXTENSION_CONSTRUCTORS(PlotExtension) EXTENSION_CONSTRUCTORS(AdvancedPlotExtension) EXTENSION_CONSTRUCTORS(LinearAlgebraExtension) EXTENSION_CONSTRUCTORS(VariableManagementExtension) EXTENSION_CONSTRUCTORS(PackagingExtension) //implement this here, as it's ";" most of the time QString ScriptExtension::commandSeparator() { - return QLatin1String(";\n"); + return QStringLiteral(";\n"); } //implement this here, as it's "#" most of the time QString ScriptExtension::commentStartingSequence() { - return QLatin1String("#"); + return QStringLiteral("#"); } //implement this here, as it's "" most of the time QString ScriptExtension::commentEndingSequence() { return QLatin1String(""); } //some convenience functions, but normally backends have a special command to create //these matrices/vectors. QString LinearAlgebraExtension::nullVector(int size, VectorType type) { QStringList values; for (int i=0;i& directives) const { QString params = QLatin1String(""); foreach (PlotDirective* dir, directives) { QString param=dispatchDirective(*dir); if (param.length()>0) params+=separatorSymbol()+param; } return plotCommand() + QLatin1String("(") + expression + params + QLatin1String(")"); } QString AdvancedPlotExtension::dispatchDirective(const PlotDirective& directive) const { const AcceptorBase* acceptor=dynamic_cast(this); if (acceptor==nullptr) { qDebug()<<"Plotting extension does not support any directives, but was asked to process one"; return QLatin1String(""); } return directive.dispatch(*acceptor); } QString AdvancedPlotExtension::separatorSymbol() const { - return QLatin1String(","); + return QStringLiteral(","); } QWidget* AdvancedPlotExtension::PlotDirective::widget(QWidget* parent) { return new QWidget(parent); } AdvancedPlotExtension::AcceptorBase::AcceptorBase() : m_widgets() { } const QVector& AdvancedPlotExtension::AcceptorBase::widgets() const { return m_widgets; } AdvancedPlotExtension::DirectiveProducer::DirectiveProducer(QWidget* parent) : QWidget(parent) { } diff --git a/src/lib/helpresult.cpp b/src/lib/helpresult.cpp index 3a54b68f..070f069d 100644 --- a/src/lib/helpresult.cpp +++ b/src/lib/helpresult.cpp @@ -1,80 +1,80 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "helpresult.h" using namespace Cantor; class Cantor::HelpResultPrivate { public: HelpResultPrivate() = default; ~HelpResultPrivate() = default; QString html; }; HelpResult::HelpResult(const QString& text, bool isHtml) : d(new HelpResultPrivate) { QString html; if (!isHtml) { html = text.toHtmlEscaped(); html.replace(QLatin1Char(' '), QLatin1String(" ")); html.replace(QLatin1Char('\n'), QLatin1String("
\n")); } else html = text; d->html = html; } int HelpResult::type() { return HelpResult::Type; } QDomElement HelpResult::toXml(QDomDocument& doc) { //No need to save results of a help request - QDomElement e=doc.createElement(QLatin1String("Result")); - e.setAttribute(QLatin1String("type"), QLatin1String("help")); + QDomElement e=doc.createElement(QStringLiteral("Result")); + e.setAttribute(QStringLiteral("type"), QStringLiteral("help")); return e; } QString HelpResult::toHtml() { return d->html; } QVariant HelpResult::data() { return QVariant(d->html); } QString HelpResult::mimeType() { - return QLatin1String("text/html"); + return QStringLiteral("text/html"); } void HelpResult::save(const QString& filename) { //No need to save results of a help request Q_UNUSED(filename); } diff --git a/src/lib/imageresult.cpp b/src/lib/imageresult.cpp index 819bbe67..e839be51 100644 --- a/src/lib/imageresult.cpp +++ b/src/lib/imageresult.cpp @@ -1,115 +1,115 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "imageresult.h" using namespace Cantor; #include #include #include #include class Cantor::ImageResultPrivate { public: ImageResultPrivate() = default; QUrl url; QImage img; QString alt; }; ImageResult::ImageResult(const QUrl &url, const QString& alt) : d(new ImageResultPrivate) { d->url=url; d->alt=alt; } ImageResult::~ImageResult() { delete d; } QString ImageResult::toHtml() { - return QString::fromLatin1("\"%2\"/").arg(d->url.toLocalFile(), d->alt); + return QStringLiteral("\"%2\"/").arg(d->url.toLocalFile(), d->alt); } QString ImageResult::toLatex() { - return QString::fromLatin1(" \\begin{center} \n \\includegraphics[width=12cm]{%1} \n \\end{center}").arg(d->url.fileName()); + return QStringLiteral(" \\begin{center} \n \\includegraphics[width=12cm]{%1} \n \\end{center}").arg(d->url.fileName()); } QVariant ImageResult::data() { if(d->img.isNull()) d->img.load(d->url.toLocalFile()); return QVariant(d->img); } QUrl ImageResult::url() { return d->url; } int ImageResult::type() { return ImageResult::Type; } QString ImageResult::mimeType() { const QList formats=QImageWriter::supportedImageFormats(); QString mimetype; foreach(const QByteArray& format, formats) { mimetype+=QLatin1String("image/"+format.toLower()+' '); } qDebug()<<"type: "<url.fileName()); + QDomElement e=doc.createElement(QStringLiteral("Result")); + e.setAttribute(QStringLiteral("type"), QStringLiteral("image")); + e.setAttribute(QStringLiteral("filename"), d->url.fileName()); qDebug()<<"done"; return e; } void ImageResult::saveAdditionalData(KZip* archive) { archive->addLocalFile(d->url.toLocalFile(), d->url.fileName()); } void ImageResult::save(const QString& filename) { //load into memory and let Qt save it, instead of just copying d->url //to give possibility to convert file format QImage img=data().value(); img.save(filename); } diff --git a/src/lib/latexrenderer.cpp b/src/lib/latexrenderer.cpp index 9f324824..f7caf52a 100644 --- a/src/lib/latexrenderer.cpp +++ b/src/lib/latexrenderer.cpp @@ -1,257 +1,257 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2011 Alexander Rieder */ #include "latexrenderer.h" using namespace Cantor; #include #include #include #include #include #include #include #include #include "settings.h" class Cantor::LatexRendererPrivate { public: QString latexCode; QString header; LatexRenderer::Method method; bool isEquationOnly; LatexRenderer::EquationType equationType; QString errorMessage; bool success; QString latexFilename; }; static const QLatin1String tex("\\documentclass[12pt,fleqn]{article}"\ "\\usepackage{latexsym,amsfonts,amssymb,ulem}"\ "\\usepackage{amsmath}"\ "\\usepackage[dvips]{graphicx}"\ "\\usepackage[utf8]{inputenc}"\ "\\usepackage{xcolor}"\ "\\setlength\\textwidth{5in}"\ "\\setlength{\\parindent}{0pt}"\ "%1"\ "\\pagecolor[rgb]{%2,%3,%4}"\ "\\pagestyle{empty}"\ "\\begin{document}"\ "\\color[rgb]{%5,%6,%7}"\ "%8"\ "\\end{document}"); static const QLatin1String eqnHeader("\\begin{eqnarray*}%1\\end{eqnarray*}"); static const QLatin1String inlineEqnHeader("$%1$"); LatexRenderer::LatexRenderer(QObject* parent) : QObject(parent), d(new LatexRendererPrivate) { d->method=LatexMethod; d->isEquationOnly=false; d->equationType=InlineEquation; d->success=false; } LatexRenderer::~LatexRenderer() { delete d; } QString LatexRenderer::latexCode() const { return d->latexCode; } void LatexRenderer::setLatexCode(const QString& src) { d->latexCode=src; } QString LatexRenderer::header() const { return d->header; } void LatexRenderer::addHeader(const QString& header) { d->header.append(header); } void LatexRenderer::setHeader(const QString& header) { d->header=header; } LatexRenderer::Method LatexRenderer::method() const { return d->method; } void LatexRenderer::setMethod(LatexRenderer::Method method) { d->method=method; } void LatexRenderer::setEquationType(LatexRenderer::EquationType type) { d->equationType=type; } LatexRenderer::EquationType LatexRenderer::equationType() const { return d->equationType; } void LatexRenderer::setErrorMessage(const QString& msg) { d->errorMessage=msg; } QString LatexRenderer::errorMessage() const { return d->errorMessage; } bool LatexRenderer::renderingSuccessful() const { return d->success; } void LatexRenderer::setEquationOnly(bool isEquationOnly) { d->isEquationOnly=isEquationOnly; } bool LatexRenderer::isEquationOnly() const { return d->isEquationOnly; } QString LatexRenderer::imagePath() const { return d->latexFilename; } void LatexRenderer::render() { switch(d->method) { case LatexRenderer::LatexMethod: renderWithLatex(); break; case LatexRenderer::MmlMethod: renderWithMml(); break; }; } void LatexRenderer::renderBlocking() { QEventLoop event; - connect(this, SIGNAL(done()), &event, SLOT(quit())); - connect(this, SIGNAL(error()), &event, SLOT(quit())); + connect(this, &LatexRenderer::done, &event, &QEventLoop::quit); + connect(this, &LatexRenderer::error, &event, &QEventLoop::quit); render(); event.exec(); } void LatexRenderer::renderWithLatex() { qDebug()<<"rendering using latex method"; QString dir=QStandardPaths::writableLocation(QStandardPaths::TempLocation); QTemporaryFile *texFile=new QTemporaryFile(dir + QDir::separator() + QLatin1String("cantor_tex-XXXXXX.tex")); texFile->open(); KColorScheme scheme(QPalette::Active); const QColor &backgroundColor=scheme.background().color(); const QColor &foregroundColor=scheme.foreground().color(); QString expressionTex=tex; expressionTex=expressionTex.arg(d->header) .arg(backgroundColor.redF()).arg(backgroundColor.greenF()).arg(backgroundColor.blueF()) .arg(foregroundColor.redF()).arg(foregroundColor.greenF()).arg(foregroundColor.blueF()); if(isEquationOnly()) { switch(equationType()) { case FullEquation: expressionTex=expressionTex.arg(eqnHeader); break; case InlineEquation: expressionTex=expressionTex.arg(inlineEqnHeader); break; } } expressionTex=expressionTex.arg(d->latexCode); // qDebug()<<"full tex:\n"<write(expressionTex.toUtf8()); texFile->flush(); QString fileName = texFile->fileName(); qDebug()<<"fileName: "<latexFilename=fileName; d->latexFilename.replace(QLatin1String(".tex"), QLatin1String(".eps")); KProcess *p=new KProcess( this ); p->setWorkingDirectory(dir); - (*p)<latexCommand()<latexCommand()<start(); } void LatexRenderer::convertToPs() { QString dviFile=d->latexFilename; dviFile.replace(QLatin1String(".eps"), QLatin1String(".dvi")); KProcess *p=new KProcess( this ); qDebug()<<"converting to eps: "<dvipsCommand()<<"-E"<<"-o"<latexFilename<dvipsCommand()<latexFilename<dvipsCommand()<latexFilename<start(); } void LatexRenderer::convertingDone() { QFileInfo info(d->latexFilename); qDebug() <<"remove temporary files for " << d->latexFilename; QString pathWithoutExtention = info.path() + QDir::separator() + info.completeBaseName(); QFile::remove(pathWithoutExtention + QLatin1String(".log")); QFile::remove(pathWithoutExtention + QLatin1String(".aux")); QFile::remove(pathWithoutExtention + QLatin1String(".tex")); QFile::remove(pathWithoutExtention + QLatin1String(".dvi")); if(info.exists()) { d->success=true; emit done(); }else { d->success=false; - setErrorMessage(QLatin1String("failed to create the latex preview image")); + setErrorMessage(QStringLiteral("failed to create the latex preview image")); emit error(); } } void LatexRenderer::renderWithMml() { qDebug()<<"WARNING: MML rendering not implemented yet!"; emit done(); } diff --git a/src/lib/latexresult.cpp b/src/lib/latexresult.cpp index 22bfd976..5b89215a 100644 --- a/src/lib/latexresult.cpp +++ b/src/lib/latexresult.cpp @@ -1,149 +1,149 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "latexresult.h" using namespace Cantor; #include #include #include class Cantor::LatexResultPrivate { public: LatexResultPrivate() { showCode=false; } bool showCode; QString code; QString plain; }; LatexResult::LatexResult(const QString& code, const QUrl &url, const QString& plain) : EpsResult( url ), d(new LatexResultPrivate) { d->code=code; d->plain=plain; } LatexResult::~LatexResult() { delete d; } int LatexResult::type() { return LatexResult::Type; } QString LatexResult::mimeType() { if(isCodeShown()) - return QLatin1String("text/plain"); + return QStringLiteral("text/plain"); else return EpsResult::mimeType(); } QString LatexResult::code() { return d->code; } QString LatexResult::plain() { return d->plain; } bool LatexResult::isCodeShown() { return d->showCode; } void LatexResult::showCode() { d->showCode=true; } void LatexResult::showRendered() { d->showCode=false; } QVariant LatexResult::data() { if(isCodeShown()) return QVariant(code()); else return EpsResult::data(); } QString LatexResult::toHtml() { if (isCodeShown()) { QString s=code(); return s.toHtmlEscaped(); } else { return EpsResult::toHtml(); } } QString LatexResult::toLatex() { return code(); } QDomElement LatexResult::toXml(QDomDocument& doc) { qDebug()<<"saving textresult "< */ #include "panelplugin.h" using namespace Cantor; #include class Cantor::PanelPluginPrivate { public: QString name; QStringList requiredExtensions; Session* session; QWidget* parentWidget; }; PanelPlugin::PanelPlugin( QObject* parent) : QObject(parent), /* KXMLGUIClient(dynamic_cast(parent)),*/ d(new PanelPluginPrivate) { d->parentWidget=nullptr; d->session=nullptr; } PanelPlugin::~PanelPlugin() { delete d; } void PanelPlugin::setParentWidget(QWidget* widget) { d->parentWidget=widget; } QWidget* PanelPlugin::parentWidget() { return d->parentWidget; } void PanelPlugin::setPluginInfo(const KPluginMetaData& info) { d->name=info.name(); - d->requiredExtensions=info.value(QLatin1String("RequiredExtensions")).split(QLatin1Char(',')); + d->requiredExtensions=info.value(QStringLiteral("RequiredExtensions")).split(QLatin1Char(',')); } QStringList PanelPlugin::requiredExtensions() { return d->requiredExtensions; } Backend::Capabilities PanelPlugin::requiredCapabilities() { return Backend::Nothing; } QString PanelPlugin::name() { return d->name; } Session* PanelPlugin::session() { return d->session; } void PanelPlugin::setSession(Session* session) { d->session=session; onSessionChanged(); } void PanelPlugin::onSessionChanged() { } diff --git a/src/lib/panelpluginhandler.cpp b/src/lib/panelpluginhandler.cpp index 754207f2..a4f0878e 100644 --- a/src/lib/panelpluginhandler.cpp +++ b/src/lib/panelpluginhandler.cpp @@ -1,135 +1,135 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2010 Alexander Rieder */ #include "panelpluginhandler.h" using namespace Cantor; #include #include #include #include #include #include "session.h" #include "panelplugin.h" #include "backend.h" class Cantor::PanelPluginHandlerPrivate { public: QList plugins; Cantor::Session* session; }; PanelPluginHandler::PanelPluginHandler( QObject* parent ) : QObject(parent) , d(new PanelPluginHandlerPrivate) { - setObjectName(QLatin1String("PanelPluginHandler")); + setObjectName(QStringLiteral("PanelPluginHandler")); d->session=nullptr; } PanelPluginHandler::~PanelPluginHandler() { delete d; } void PanelPluginHandler::loadPlugins() { if(d->session==nullptr) return; qDebug()<<"loading panel plugins for session of type "<session->backend()->name(); QStringList panelDirs; foreach(const QString &dir, QCoreApplication::libraryPaths()){ panelDirs << dir + QDir::separator() + QLatin1String("cantor/panels"); } QPluginLoader loader; const Cantor::Backend::Capabilities capabilities = d->session->backend()->capabilities(); const QStringList& extensions = d->session->backend()->extensions(); foreach(const QString &dir, panelDirs){ qDebug() << "dir: " << dir; QStringList panels; QDir panelDir = QDir(dir); panels = panelDir.entryList(); foreach (const QString &panel, panels){ if (panel==QLatin1String(".") || panel==QLatin1String("..")) continue; loader.setFileName(dir + QDir::separator() + panel); if (!loader.load()){ qDebug() << "Error while loading panel: " << panel; continue; } KPluginFactory* factory = KPluginLoader(loader.fileName()).factory(); PanelPlugin* plugin = factory->create(this); KPluginMetaData info(loader); plugin->setPluginInfo(info); bool supported=true; foreach(const QString& req, plugin->requiredExtensions()){ // FIXME: That req.isEmpty() is there just because Help Panel has req // empty, returning FALSE when the comparison must to return TRUE. supported = supported && (extensions.contains(req) || req.isEmpty()); } supported = supported && ( (capabilities & plugin->requiredCapabilities()) == plugin->requiredCapabilities()); if(supported) { qDebug() << "plugin " << info.name()<<" is supported, requires extensions " << plugin->requiredExtensions(); d->plugins.append(plugin); plugin->setSession(d->session); }else { qDebug() << "plugin " << info.name() <<" is not supported"; plugin->deleteLater(); } } } emit pluginsChanged(); } void PanelPluginHandler::setSession(Session* session) { qDeleteAll(d->plugins); d->plugins.clear(); d->session=session; loadPlugins(); } QList PanelPluginHandler::plugins() { return d->plugins; } void PanelPluginHandler::addPlugin(PanelPlugin* plugin) { d->plugins.append(plugin); } diff --git a/src/lib/result.cpp b/src/lib/result.cpp index 0c302b1c..ffa6696d 100644 --- a/src/lib/result.cpp +++ b/src/lib/result.cpp @@ -1,65 +1,65 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "result.h" using namespace Cantor; #include #include class Cantor::ResultPrivate { public: }; Result::Result() : d(new ResultPrivate) { } Result::~Result() { delete d; } QUrl Result::url() { return QUrl(); } QString Result::toLatex() { QString html=toHtml(); //replace linebreaks - html.replace(QRegExp(QLatin1String("
[\n]")), QLatin1String("\n")); + html.replace(QRegExp(QLatin1String("
[\n]")), QStringLiteral("\n")); //remove all the unknown tags html.remove( QRegExp( QLatin1String("<[a-zA-Z\\/][^>]*>") ) ); - return QString::fromLatin1("\\begin{verbatim} %1 \\end{verbatim}").arg(html); + return QStringLiteral("\\begin{verbatim} %1 \\end{verbatim}").arg(html); } void Result::saveAdditionalData(KZip* archive) { Q_UNUSED(archive) //Do nothing } diff --git a/src/lib/syntaxhelpobject.cpp b/src/lib/syntaxhelpobject.cpp index 445ec2e7..286f2c75 100644 --- a/src/lib/syntaxhelpobject.cpp +++ b/src/lib/syntaxhelpobject.cpp @@ -1,72 +1,72 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "syntaxhelpobject.h" using namespace Cantor; #include "session.h" #include class Cantor::SyntaxHelpObjectPrivate{ public: QString command; Cantor::Session* session; QString htmlResult; }; SyntaxHelpObject::SyntaxHelpObject(const QString& command, Cantor::Session* session) : QObject(session), d(new SyntaxHelpObjectPrivate) { d->command=command; d->session=session; } SyntaxHelpObject::~SyntaxHelpObject() { delete d; } void SyntaxHelpObject::fetchSyntaxHelp() { //Start a delayed fetch - QTimer::singleShot(0, this, SLOT(fetchInformation())); + QTimer::singleShot(0, this, &SyntaxHelpObject::fetchInformation); } QString SyntaxHelpObject::toHtml() { return d->htmlResult; } void SyntaxHelpObject::setHtml(const QString& result) { d->htmlResult=result; } QString SyntaxHelpObject::command() { return d->command; } Session* SyntaxHelpObject::session() { return d->session; } diff --git a/src/lib/textresult.cpp b/src/lib/textresult.cpp index dde5b927..c070c862 100644 --- a/src/lib/textresult.cpp +++ b/src/lib/textresult.cpp @@ -1,124 +1,124 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "textresult.h" using namespace Cantor; #include #include #include class Cantor::TextResultPrivate { public: TextResultPrivate() { format=TextResult::PlainTextFormat; } QString data; QString plain; TextResult::Format format; }; TextResult::TextResult(const QString& data) : d(new TextResultPrivate) { d->data=data.trimmed(); d->plain=data.trimmed(); } TextResult::TextResult(const QString& data, const QString& plain) : d(new TextResultPrivate) { d->data=data.trimmed(); d->plain=plain.trimmed(); } TextResult::~TextResult() { delete d; } QString TextResult::toHtml() { QString s=d->data.toHtmlEscaped(); s.replace(QLatin1Char('\n'), QLatin1String("
\n")); return s; } QVariant TextResult::data() { return QVariant(d->data); } QString TextResult::plain() { return d->plain; } int TextResult::type() { return TextResult::Type; } QString TextResult::mimeType() { qDebug()<<"format: "<format; } void TextResult::setFormat(TextResult::Format f) { d->format=f; } QDomElement TextResult::toXml(QDomDocument& doc) { qDebug()<<"saving textresult "<data; file.close(); } diff --git a/src/scripteditor/scripteditorwidget.cpp b/src/scripteditor/scripteditorwidget.cpp index f4d7b712..5cf05efe 100644 --- a/src/scripteditor/scripteditorwidget.cpp +++ b/src/scripteditor/scripteditorwidget.cpp @@ -1,153 +1,153 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #include "scripteditorwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ScriptEditorWidget::ScriptEditorWidget(const QString& filter, const QString& highlightingMode, QWidget* parent) : KXmlGuiWindow(parent), m_filter(filter), m_editor(nullptr), m_script(nullptr), m_tmpFile(nullptr) { - setObjectName(QLatin1String("ScriptEditor")); + setObjectName(QStringLiteral("ScriptEditor")); KStandardAction::openNew(this, SLOT(newScript()), actionCollection()); KStandardAction::open(this, SLOT(open()), actionCollection()); KStandardAction::close(this, SLOT(close()), actionCollection()); - QAction * runAction = actionCollection()->addAction(QLatin1String("file_execute"), this, SLOT(run())); - runAction->setIcon(QIcon::fromTheme(QLatin1String("system-run"))); + QAction * runAction = actionCollection()->addAction(QStringLiteral("file_execute"), this, SLOT(run())); + runAction->setIcon(QIcon::fromTheme(QStringLiteral("system-run"))); runAction->setText(i18n("Run Script")); KTextEditor::Editor* editor = KTextEditor::Editor::instance(); if (!editor) { KMessageBox::error(this, i18n("A KDE text-editor component could not be found;\n" "please check your KDE installation.")); } else { m_script=editor->createDocument(nullptr); m_editor=qobject_cast(m_script->createView(this)); m_script->setHighlightingMode(highlightingMode); KConfigGroup cg(KSharedConfig::openConfig(), "ScriptEditor"); setAutoSaveSettings(cg, true); setCentralWidget(m_editor); - setupGUI(QSize(500,600), Default, QLatin1String("cantor_scripteditor.rc")); + setupGUI(QSize(500,600), Default, QStringLiteral("cantor_scripteditor.rc")); guiFactory()->addClient(m_editor); KWindowConfig::restoreWindowSize(this->windowHandle(), cg); connect(m_script, &KTextEditor::Document::modifiedChanged, this, &ScriptEditorWidget::updateCaption); connect(m_script, &KTextEditor::Document::documentUrlChanged, this, &ScriptEditorWidget::updateCaption); updateCaption(); } } void ScriptEditorWidget::newScript() { QString highlightingMode = m_script->highlightingMode(); m_script->closeUrl(); m_script->setHighlightingMode(highlightingMode); } void ScriptEditorWidget::open() { QUrl url = QFileDialog::getOpenFileUrl(this, QString(), QUrl(), m_filter); m_script->openUrl(url); } -void ScriptEditorWidget::open(QUrl url) +void ScriptEditorWidget::open(const QUrl &url) { m_script->openUrl(url); } void ScriptEditorWidget::run() { QString filename; if(!m_script->url().isLocalFile()) { // If the script is not in a local file, write it to a temporary file if(m_tmpFile==nullptr) { m_tmpFile=new QTemporaryFile(); } else { m_tmpFile->resize(0); } m_tmpFile->open(); QString text=m_script->text(); m_tmpFile->write(text.toUtf8()); m_tmpFile->close(); filename=m_tmpFile->fileName(); }else { m_script->save(); filename=m_script->url().toLocalFile(); } qDebug()<<"running "<queryClose(); else return true; } void ScriptEditorWidget::updateCaption() { QString fileName = m_script->url().toLocalFile(); bool modified = m_script->isModified(); if (fileName.isEmpty()) { setCaption(i18n("Script Editor"), modified); }else { setCaption(i18n("Script Editor - %1", fileName), modified); } } diff --git a/src/scripteditor/scripteditorwidget.h b/src/scripteditor/scripteditorwidget.h index b13d0b9c..2ae491b0 100644 --- a/src/scripteditor/scripteditorwidget.h +++ b/src/scripteditor/scripteditorwidget.h @@ -1,62 +1,62 @@ /* 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Copyright (C) 2009 Alexander Rieder */ #ifndef _SCRIPTEDITORWIDGET_H #define _SCRIPTEDITORWIDGET_H #include class QTemporaryFile; class QGridLayout; namespace KTextEditor { class View; class Document; } class ScriptEditorWidget : public KXmlGuiWindow { Q_OBJECT public: explicit ScriptEditorWidget( const QString& filter, const QString& highlightingMode, QWidget* parent = nullptr ); ~ScriptEditorWidget() override = default; - void open(QUrl url); + void open(const QUrl &url); Q_SIGNALS: void runScript(const QString& filename); private Q_SLOTS: void newScript(); void open(); void run(); void updateCaption(); protected: bool queryClose() override; private: QString m_filter; KTextEditor::View* m_editor; KTextEditor::Document* m_script; QTemporaryFile* m_tmpFile; }; #endif /* _SCRIPTEDITORWIDGET_H */