From a2c9ad6e2951d96c2c9e3055950cc8097f1d0e85 Mon Sep 17 00:00:00 2001 From: Zacharias-Brohn Date: Wed, 4 Mar 2026 20:06:58 +0100 Subject: [PATCH] qalc --- Plugins/ZShell/CMakeLists.txt | 1 + Plugins/ZShell/qalculator.cpp | 52 +++++++++++++++++++++++++++++++++++ Plugins/ZShell/qalculator.hpp | 19 +++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 Plugins/ZShell/qalculator.cpp create mode 100644 Plugins/ZShell/qalculator.hpp diff --git a/Plugins/ZShell/CMakeLists.txt b/Plugins/ZShell/CMakeLists.txt index bde2f00..d27e282 100644 --- a/Plugins/ZShell/CMakeLists.txt +++ b/Plugins/ZShell/CMakeLists.txt @@ -43,6 +43,7 @@ qml_module(ZShell imageanalyser.hpp imageanalyser.cpp requests.hpp requests.cpp toaster.hpp toaster.cpp + qalculator.hpp qalculator.cpp LIBRARIES Qt::Gui Qt::Quick diff --git a/Plugins/ZShell/qalculator.cpp b/Plugins/ZShell/qalculator.cpp new file mode 100644 index 0000000..c58962f --- /dev/null +++ b/Plugins/ZShell/qalculator.cpp @@ -0,0 +1,52 @@ +#include "qalculator.hpp" + +#include + +namespace ZShell { + +Qalculator::Qalculator(QObject* parent) + : QObject(parent) { + if (!CALCULATOR) { + new Calculator(); + CALCULATOR->loadExchangeRates(); + CALCULATOR->loadGlobalDefinitions(); + CALCULATOR->loadLocalDefinitions(); + } +} + +QString Qalculator::eval(const QString& expr, bool printExpr) const { + if (expr.isEmpty()) { + return QString(); + } + + EvaluationOptions eo; + PrintOptions po; + + std::string parsed; + std::string result = CALCULATOR->calculateAndPrint( + CALCULATOR->unlocalizeExpression(expr.toStdString(), eo.parse_options), 100, eo, po, &parsed); + + std::string error; + while (CALCULATOR->message()) { + if (!CALCULATOR->message()->message().empty()) { + if (CALCULATOR->message()->type() == MESSAGE_ERROR) { + error += "error: "; + } else if (CALCULATOR->message()->type() == MESSAGE_WARNING) { + error += "warning: "; + } + error += CALCULATOR->message()->message(); + } + CALCULATOR->nextMessage(); + } + if (!error.empty()) { + return QString::fromStdString(error); + } + + if (printExpr) { + return QString("%1 = %2").arg(parsed).arg(result); + } + + return QString::fromStdString(result); +} + +} // namespace ZShell diff --git a/Plugins/ZShell/qalculator.hpp b/Plugins/ZShell/qalculator.hpp new file mode 100644 index 0000000..348a4b7 --- /dev/null +++ b/Plugins/ZShell/qalculator.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +namespace ZShell { + +class Qalculator : public QObject { +Q_OBJECT +QML_ELEMENT +QML_SINGLETON + +public: +explicit Qalculator(QObject* parent = nullptr); + +Q_INVOKABLE QString eval(const QString& expr, bool printExpr = true) const; +}; + +} // namespace ZShell