diff --git a/CMakeLists.txt b/CMakeLists.txt index 9109c24..65146d0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,121 +1,121 @@ cmake_minimum_required(VERSION 3.0) set(KF5_VERSION "5.50.0") # handled by release scripts project(KI18n VERSION ${KF5_VERSION}) # ECM setup include(FeatureSummary) find_package(ECM 5.49.0 NO_MODULE) set_package_properties(ECM PROPERTIES TYPE REQUIRED DESCRIPTION "Extra CMake Modules." URL "https://projects.kde.org/projects/kdesupport/extra-cmake-modules") feature_summary(WHAT REQUIRED_PACKAGES_NOT_FOUND FATAL_ON_MISSING_REQUIRED_PACKAGES) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR} ${KI18n_SOURCE_DIR}/cmake ${KI18n_BINARY_DIR}/cmake) include(GenerateExportHeader) include(CMakePackageConfigHelpers) include(ECMSetupVersion) include(ECMGenerateHeaders) include(ECMAddQch) ecm_setup_version( PROJECT VARIABLE_PREFIX KI18N VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/ki18n_version.h" PACKAGE_VERSION_FILE "${CMAKE_BINARY_DIR}/cmake/KF5I18nConfigVersion.cmake" SOVERSION 5) # Dependencies set(REQUIRED_QT_VERSION 5.8.0) find_package(Qt5 ${REQUIRED_QT_VERSION} CONFIG REQUIRED Core) -option(BUILD_WITH_QTSCRIPT "Build with support for scripted translations (recommended)" ON) -if (BUILD_WITH_QTSCRIPT) - find_package(Qt5Script ${REQUIRED_QT_VERSION} CONFIG REQUIRED) +option(BUILD_WITH_QML "Build with support for scripted translations (recommended)" ON) +if (BUILD_WITH_QML) + find_package(Qt5Qml ${REQUIRED_QT_VERSION} CONFIG REQUIRED) endif() include(KDEInstallDirs) include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) include(KDECMakeSettings) find_package(LibIntl) set_package_properties(LibIntl PROPERTIES TYPE REQUIRED URL "http://gnuwin32.sourceforge.net/packages/libintl.htm" PURPOSE "Needed for building KI18n unless glibc is the system libc implementation" ) # KF5I18nMacros.cmake only needs to know the python executable path. # Due to CMake caching the variables, and KF5I18nMacros being included by KF5I18nConfig, # we have to hardcode the PYTHON_EXECUTABLE path or anything depending on KF5I18n # would be unable to find another Python version. find_package(PythonInterp REQUIRED) configure_file(cmake/KF5I18nMacros.cmake.in ${KI18n_BINARY_DIR}/cmake/KF5I18nMacros.cmake @ONLY) # Needed to build the ki18n translations and run the autotests file(COPY ${KI18n_SOURCE_DIR}/cmake/build-pofiles.cmake DESTINATION ${KI18n_BINARY_DIR}/cmake) file(COPY ${KI18n_SOURCE_DIR}/cmake/build-tsfiles.cmake DESTINATION ${KI18n_BINARY_DIR}/cmake) file(COPY ${KI18n_SOURCE_DIR}/cmake/ts-pmap-compile.py DESTINATION ${KI18n_BINARY_DIR}/cmake) file(COPY ${KI18n_SOURCE_DIR}/cmake/kf5i18nuic.cmake DESTINATION ${KI18n_BINARY_DIR}/cmake) # Create dummy file to execute find_package(KF5I18n) within autotests/ki18n_install file(WRITE ${CMAKE_BINARY_DIR}/cmake/KF5I18nTargets.cmake "") include(${KI18n_BINARY_DIR}/cmake/KF5I18nMacros.cmake) remove_definitions(-DQT_NO_CAST_FROM_BYTEARRAY) if(MSVC) remove_definitions(-DQT_STRICT_ITERATORS) endif() option(BUILD_QCH "Build API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)" OFF) add_feature_info(QCH ${BUILD_QCH} "API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)") if (IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/po") ki18n_install(po) endif() add_subdirectory(src) if (BUILD_TESTING) add_subdirectory(autotests) endif() configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/src/config.h") # create a Config.cmake and a ConfigVersion.cmake file and install them set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/KF5I18n") if (BUILD_QCH) ecm_install_qch_export( TARGETS KF5I18n_QCH FILE KF5I18nQchTargets.cmake DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) set(PACKAGE_INCLUDE_QCHTARGETS "include(\"\${CMAKE_CURRENT_LIST_DIR}/KF5I18nQchTargets.cmake\")") endif() configure_package_config_file("${CMAKE_CURRENT_LIST_DIR}/KF5I18nConfig.cmake.in" "${CMAKE_BINARY_DIR}/cmake/KF5I18nConfig.cmake" INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR} PATH_VARS KF5_INCLUDE_INSTALL_DIR LIB_INSTALL_DIR CMAKE_INSTALL_PREFIX) install(FILES "${CMAKE_BINARY_DIR}/cmake/KF5I18nConfig.cmake" "${CMAKE_BINARY_DIR}/cmake/KF5I18nConfigVersion.cmake" DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel) install(EXPORT KF5I18nTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}" FILE KF5I18nTargets.cmake NAMESPACE KF5::) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ki18n_version.h DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF5} COMPONENT Devel) install( FILES ${KI18n_BINARY_DIR}/cmake/KF5I18nMacros.cmake cmake/kf5i18nuic.cmake cmake/build-pofiles.cmake cmake/build-tsfiles.cmake cmake/ts-pmap-compile.py DESTINATION ${CMAKECONFIG_INSTALL_DIR} COMPONENT Devel ) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt index 867c2f2..7f5d022 100644 --- a/autotests/CMakeLists.txt +++ b/autotests/CMakeLists.txt @@ -1,49 +1,49 @@ remove_definitions(-DQT_NO_CAST_FROM_ASCII) include(ECMAddTests) find_package(Qt5 ${REQUIRED_QT_VERSION} CONFIG REQUIRED Test Qml Concurrent) ecm_add_test(ki18ndeclarativetest.cpp TEST_NAME "ki18n-declarativetest" LINK_LIBRARIES Qt5::Test Qt5::Qml KF5::I18n ) ecm_add_test(klocalizedstringtest.cpp TEST_NAME "ki18n-klocalizedstringtest" LINK_LIBRARIES Qt5::Test Qt5::Concurrent KF5::I18n ${LibIntl_LIBRARIES} ) # klocalizedstringtest needs the libintl include path target_include_directories(ki18n-klocalizedstringtest PRIVATE ${LibIntl_INCLUDE_DIRS}) if (TARGET ktranscript) ecm_add_test(ktranscripttest.cpp testhelpers.cpp TEST_NAME "ki18n-ktranscripttest" LINK_LIBRARIES Qt5::Test KF5::I18n ) # ktranscripttest needs the path to ktranscript in the build dir: it cannot rely # on the installed version since it must be able to run *before* the plugin is # installed. target_compile_definitions(ki18n-ktranscripttest PRIVATE "KTRANSCRIPT_PATH=\"$\"") # ktranscriptcleantest needs to directly compile ktranscript.cpp with an addition DEFINE ecm_add_test(ktranscriptcleantest.cpp ../src/ktranscript.cpp ../src/common_helpers.cpp TEST_NAME ki18n-ktranscriptcleantest - LINK_LIBRARIES Qt5::Script Qt5::Test Qt5::Concurrent KF5::I18n + LINK_LIBRARIES Qt5::Qml Qt5::Test Qt5::Concurrent KF5::I18n ) target_compile_definitions(ki18n-ktranscriptcleantest PRIVATE "KTRANSCRIPT_TESTBUILD") target_include_directories(ki18n-ktranscriptcleantest PRIVATE ..) endif() add_test(ki18n_install ${CMAKE_CTEST_COMMAND} --build-and-test "${CMAKE_CURRENT_SOURCE_DIR}/ki18n_install" "${CMAKE_CURRENT_BINARY_DIR}/ki18n_install" --build-generator ${CMAKE_GENERATOR} --build-makeprogram ${CMAKE_MAKE_PROGRAM} --build-target install --build-options "-DCMAKE_MODULE_PATH=${CMAKE_MODULE_PATH}" "-DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/ki18n_install/destdir" "-DKF5I18n_DIR=${CMAKE_BINARY_DIR}/cmake" --test-command ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_SOURCE_DIR}/ki18n_install/test.cmake") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 493860a..28102a5 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,107 +1,107 @@ set(libki18n_SRCS klocalizedstring.cpp klocalizedtranslator.cpp kcatalog.cpp kuitmarkup.cpp common_helpers.cpp klocalizedcontext.cpp main.cpp ) add_library(KF5I18n ${libki18n_SRCS}) generate_export_header(KF5I18n BASE_NAME KI18n) add_library(KF5::I18n ALIAS KF5I18n) target_include_directories(KF5I18n INTERFACE "$") target_include_directories(KF5I18n PRIVATE ${LibIntl_INCLUDE_DIRS}) target_link_libraries(KF5I18n PUBLIC Qt5::Core) # This is only required for platforms which don't use glibc (with glibc LibIntl_LIBRARIES will be empty) target_link_libraries(KF5I18n PRIVATE ${LibIntl_LIBRARIES}) target_compile_options(KF5I18n PRIVATE -DTRANSLATION_DOMAIN=\"ki18n5\") set_target_properties(KF5I18n PROPERTIES VERSION ${KI18N_VERSION_STRING} SOVERSION ${KI18N_SOVERSION} EXPORT_NAME I18n ) install(TARGETS KF5I18n EXPORT KF5I18nTargets ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) ecm_generate_headers(KI18n_HEADERS HEADER_NAMES KLocalizedContext KLocalizedString KLocalizedTranslator KuitMarkup KuitSetup REQUIRED_HEADERS KI18n_HEADERS ) find_package(PythonModuleGeneration) if (PythonModuleGeneration_FOUND) ecm_generate_python_binding( TARGET KF5::I18n PYTHONNAMESPACE PyKF5 MODULENAME KI18n RULES_FILE "${CMAKE_SOURCE_DIR}/cmake/rules_PyKF5.py" INSTALL_DIR_SUFFIX ${KDE_INSTALL_PYTHONBINDINGSDIR} SIP_DEPENDS QtCore/QtCoremod.sip HEADERS klocalizedcontext.h klocalizedstring.h klocalizedtranslator.h kuitmarkup.h kuitsetup.h ) endif() install(FILES ${KI18n_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/ki18n_export.h DESTINATION "${KDE_INSTALL_INCLUDEDIR_KF5}/KI18n" COMPONENT Devel ) ### ktranscript plugin -if (BUILD_WITH_QTSCRIPT) +if (BUILD_WITH_QML) set(ktranscript_LIB_SRCS ktranscript.cpp common_helpers.cpp ) add_library(ktranscript MODULE ${ktranscript_LIB_SRCS}) generate_export_header(ktranscript BASE_NAME KTranscript) -target_link_libraries(ktranscript PRIVATE Qt5::Script Qt5::Core) +target_link_libraries(ktranscript PRIVATE Qt5::Qml Qt5::Core) install(TARGETS ktranscript DESTINATION ${KDE_INSTALL_PLUGINDIR}/kf5) endif() if (BUILD_QCH) ecm_add_qch( KF5I18n_QCH NAME KI18n BASE_NAME KF5I18n VERSION ${KF5_VERSION} ORG_DOMAIN org.kde SOURCES # using only public headers, to cover only public API ${KI18n_HEADERS} "${CMAKE_SOURCE_DIR}/docs/programmers-guide.md" "${CMAKE_SOURCE_DIR}/docs/translators-guide.md" MD_MAINPAGE "${CMAKE_SOURCE_DIR}/README.md" LINK_QCHS Qt5Core_QCH BLANK_MACROS KI18N_EXPORT KI18N_DEPRECATED_EXPORT KI18N_DEPRECATED TAGFILE_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} QCH_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} COMPONENT Devel ) endif() include(ECMGeneratePriFile) ecm_generate_pri_file(BASE_NAME KI18n LIB_NAME KF5I18n DEPS "core" FILENAME_VAR PRI_FILENAME INCLUDE_INSTALL_DIR ${KDE_INSTALL_INCLUDEDIR_KF5}/KI18n) install(FILES ${PRI_FILENAME} DESTINATION ${ECM_MKSPECS_INSTALL_DIR}) diff --git a/src/ktranscript.cpp b/src/ktranscript.cpp index 73dbc6c..cc17536 100644 --- a/src/ktranscript.cpp +++ b/src/ktranscript.cpp @@ -1,1692 +1,1618 @@ /* This file is part of the KDE libraries Copyright (C) 2007 Chusslove Illich Copyright (C) 2014 Kevin Krammer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include //#include -#include -#include +#include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include #include class KTranscriptImp; class Scriptface; typedef QHash TsConfigGroup; typedef QHash TsConfig; // Transcript implementation (used as singleton). class KTranscriptImp : public KTranscript { public: KTranscriptImp(); ~KTranscriptImp() override; QString eval(const QList &argv, const QString &lang, const QString &ctry, const QString &msgctxt, const QHash &dynctxt, const QString &msgid, const QStringList &subs, const QList &vals, const QString &ftrans, QList &mods, QString &error, bool &fallback) override; QStringList postCalls(const QString &lang) override; // Lexical path of the module for the executing code. QString currentModulePath; private: void loadModules(const QList &mods, QString &error); void setupInterpreter(const QString &lang); TsConfig config; QHash m_sface; }; // Script-side transcript interface. -class Scriptface : public QObject, public QScriptable +class Scriptface : public QObject { Q_OBJECT public: explicit Scriptface(const TsConfigGroup &config, QObject *parent = nullptr); ~Scriptface(); // Interface functions. - Q_INVOKABLE QScriptValue load(); // actually has variable length argument list - Q_INVOKABLE QScriptValue setcall(const QScriptValue &name, const QScriptValue &func, - const QScriptValue &fval = QScriptValue::NullValue); - Q_INVOKABLE QScriptValue hascall(const QScriptValue &name); - Q_INVOKABLE QScriptValue acall(); // actually has variable length argument list - Q_INVOKABLE QScriptValue setcallForall(const QScriptValue &name, const QScriptValue &func, - const QScriptValue &fval = QScriptValue::NullValue); - Q_INVOKABLE QScriptValue fallback(); - Q_INVOKABLE QScriptValue nsubs(); - Q_INVOKABLE QScriptValue subs(const QScriptValue &index); - Q_INVOKABLE QScriptValue vals(const QScriptValue &index); - Q_INVOKABLE QScriptValue msgctxt(); - Q_INVOKABLE QScriptValue dynctxt(const QScriptValue &key); - Q_INVOKABLE QScriptValue msgid(); - Q_INVOKABLE QScriptValue msgkey(); - Q_INVOKABLE QScriptValue msgstrf(); - Q_INVOKABLE QScriptValue dbgputs(const QScriptValue &str); - Q_INVOKABLE QScriptValue warnputs(const QScriptValue &str); - Q_INVOKABLE QScriptValue localeCountry(); - Q_INVOKABLE QScriptValue normKey(const QScriptValue &phrase); - Q_INVOKABLE QScriptValue loadProps(); // actually has variable length argument list - Q_INVOKABLE QScriptValue getProp(const QScriptValue &phrase, const QScriptValue &prop); - Q_INVOKABLE QScriptValue setProp(const QScriptValue &phrase, const QScriptValue &prop, const QScriptValue &value); - Q_INVOKABLE QScriptValue toUpperFirst(const QScriptValue &str, const QScriptValue &nalt = QScriptValue::NullValue); - Q_INVOKABLE QScriptValue toLowerFirst(const QScriptValue &str, const QScriptValue &nalt = QScriptValue::NullValue); - Q_INVOKABLE QScriptValue getConfString(const QScriptValue &key, const QScriptValue &dval = QScriptValue::NullValue); - Q_INVOKABLE QScriptValue getConfBool(const QScriptValue &key, const QScriptValue &dval = QScriptValue::NullValue); - Q_INVOKABLE QScriptValue getConfNumber(const QScriptValue &key, const QScriptValue &dval = QScriptValue::NullValue); + Q_INVOKABLE QJSValue load(const QString &name); + Q_INVOKABLE QJSValue setcall(const QJSValue &name, const QJSValue &func, + const QJSValue &fval = QJSValue::NullValue); + Q_INVOKABLE QJSValue hascall(const QString &name); + Q_INVOKABLE QJSValue acallInternal(const QJSValue &args); + Q_INVOKABLE QJSValue setcallForall(const QJSValue &name, const QJSValue &func, + const QJSValue &fval = QJSValue::NullValue); + Q_INVOKABLE QJSValue fallback(); + Q_INVOKABLE QJSValue nsubs(); + Q_INVOKABLE QJSValue subs(const QJSValue &index); + Q_INVOKABLE QJSValue vals(const QJSValue &index); + Q_INVOKABLE QJSValue msgctxt(); + Q_INVOKABLE QJSValue dynctxt(const QString &key); + Q_INVOKABLE QJSValue msgid(); + Q_INVOKABLE QJSValue msgkey(); + Q_INVOKABLE QJSValue msgstrf(); + Q_INVOKABLE void dbgputs(const QString &str); + Q_INVOKABLE void warnputs(const QString &str); + Q_INVOKABLE QJSValue localeCountry(); + Q_INVOKABLE QJSValue normKey(const QJSValue &phrase); + Q_INVOKABLE QJSValue loadProps(const QString &name); + Q_INVOKABLE QJSValue getProp(const QJSValue &phrase, const QJSValue &prop); + Q_INVOKABLE QJSValue setProp(const QJSValue &phrase, const QJSValue &prop, const QJSValue &value); + Q_INVOKABLE QJSValue toUpperFirst(const QJSValue &str, const QJSValue &nalt = QJSValue::NullValue); + Q_INVOKABLE QJSValue toLowerFirst(const QJSValue &str, const QJSValue &nalt = QJSValue::NullValue); + Q_INVOKABLE QJSValue getConfString(const QJSValue &key, const QJSValue &dval = QJSValue::NullValue); + Q_INVOKABLE QJSValue getConfBool(const QJSValue &key, const QJSValue &dval = QJSValue::NullValue); + Q_INVOKABLE QJSValue getConfNumber(const QJSValue &key, const QJSValue &dval = QJSValue::NullValue); // Helper methods to interface functions. - QScriptValue load(const QScriptValueList &fnames); + QJSValue load(const QJSValueList &names); + QJSValue loadProps(const QJSValueList &names); QString loadProps_text(const QString &fpath); QString loadProps_bin(const QString &fpath); QString loadProps_bin_00(const QString &fpath); QString loadProps_bin_01(const QString &fpath); - void put(const QString &propertyName, const QScriptValue &value); + void put(const QString &propertyName, const QJSValue &value); // Link to its script engine - QScriptEngine *const scriptEngine; + QJSEngine *const scriptEngine; // Current message data. const QString *msgcontext; const QHash *dyncontext; const QString *msgId; const QStringList *subList; const QList *valList; const QString *ftrans; const QString *ctry; // Fallback request handle. bool *fallbackRequest; // Function register. - QHash funcs; - QHash fvals; + QHash funcs; + QHash fvals; QHash fpaths; // Ordering of those functions which execute for all messages. QList nameForalls; // Property values per phrase (used by *Prop interface calls). // Not QStrings, in order to avoid conversion from UTF-8 when // loading compiled maps (less latency on startup). QHash > phraseProps; // Unresolved property values per phrase, // containing the pointer to compiled pmap file handle and offset in it. QHash > phraseUnparsedProps; QHash resolveUnparsedProps(const QByteArray &phrase); // Set of loaded pmap files by paths and file handle pointers. QSet loadedPmapPaths; QSet loadedPmapHandles; // User config. TsConfigGroup config; }; // ---------------------------------------------------------------------- // Custom debug and warning output (kdebug not available) #define DBGP "KTranscript: " void dbgout(const char *str) { #ifndef NDEBUG fprintf(stderr, DBGP"%s\n", str); #else Q_UNUSED(str); #endif } template void dbgout(const char *str, const T1 &a1) { #ifndef NDEBUG fprintf(stderr, DBGP"%s\n", QString::fromUtf8(str).arg(a1).toLocal8Bit().data()); #else Q_UNUSED(str); Q_UNUSED(a1); #endif } template void dbgout(const char *str, const T1 &a1, const T2 &a2) { #ifndef NDEBUG fprintf(stderr, DBGP"%s\n", QString::fromUtf8(str).arg(a1).arg(a2).toLocal8Bit().data()); #else Q_UNUSED(str); Q_UNUSED(a1); Q_UNUSED(a2); #endif } template void dbgout(const char *str, const T1 &a1, const T2 &a2, const T3 &a3) { #ifndef NDEBUG fprintf(stderr, DBGP"%s\n", QString::fromUtf8(str).arg(a1).arg(a2).arg(a3).toLocal8Bit().data()); #else Q_UNUSED(str); Q_UNUSED(a1); Q_UNUSED(a2); Q_UNUSED(a3); #endif } #define WARNP "KTranscript: " void warnout(const char *str) { fprintf(stderr, WARNP"%s\n", str); } template void warnout(const char *str, const T1 &a1) { fprintf(stderr, WARNP"%s\n", QString::fromUtf8(str).arg(a1).toLocal8Bit().data()); } // ---------------------------------------------------------------------- // Produces a string out of a script exception. -QString expt2str(QScriptEngine *engine) +QString expt2str(const QJSValue &expt) { - const QScriptValue expt = engine->uncaughtException(); - if (expt.isObject()) { - const QScriptValue message = expt.toObject().property(QStringLiteral("message")); - if (message.isValid()) { + if (expt.isError()) { + const QJSValue message = expt.property(QStringLiteral("message")); + if (!message.isUndefined()) { return QStringLiteral("Error: %1").arg(message.toString()); } } QString strexpt = expt.toString(); return QStringLiteral("Caught exception: %1").arg(strexpt); } // ---------------------------------------------------------------------- // Count number of lines in the string, // up to and excluding the requested position. int countLines(const QString &s, int p) { int n = 1; int len = s.length(); for (int i = 0; i < p && i < len; ++i) { if (s[i] == QLatin1Char('\n')) { ++n; } } return n; } // ---------------------------------------------------------------------- // Normalize string key for hash lookups, QByteArray normKeystr(const QString &raw, bool mayHaveAcc = true) { // NOTE: Regexes should not be used here for performance reasons. // This function may potentially be called thousands of times // on application startup. QString key = raw; // Strip all whitespace. int len = key.length(); QString nkey; for (int i = 0; i < len; ++i) { QChar c = key[i]; if (!c.isSpace()) { nkey.append(c); } } key = nkey; // Strip accelerator marker. if (mayHaveAcc) { key = removeAcceleratorMarker(key); } // Convert to lower case. key = key.toLower(); return key.toUtf8(); } // ---------------------------------------------------------------------- // Trim multiline string in a "smart" way: // Remove leading and trailing whitespace up to and including first // newline from that side, if there is one; otherwise, don't touch. QString trimSmart(const QString &raw) { // NOTE: This could be done by a single regex, but is not due to // performance reasons. // This function may potentially be called thousands of times // on application startup. int len = raw.length(); int is = 0; while (is < len && raw[is].isSpace() && raw[is] != QLatin1Char('\n')) { ++is; } if (is >= len || raw[is] != QLatin1Char('\n')) { is = -1; } int ie = len - 1; while (ie >= 0 && raw[ie].isSpace() && raw[ie] != QLatin1Char('\n')) { --ie; } if (ie < 0 || raw[ie] != QLatin1Char('\n')) { ie = len; } return raw.mid(is + 1, ie - is - 1); } // ---------------------------------------------------------------------- // Produce a JavaScript object out of Qt variant. -QScriptValue variantToJsValue(const QVariant &val) +QJSValue variantToJsValue(const QVariant &val) { QVariant::Type vtype = val.type(); if (vtype == QVariant::String) { - return QScriptValue(val.toString()); + return QJSValue(val.toString()); } else if (vtype == QVariant::Bool) { - return QScriptValue(val.toBool()); + return QJSValue(val.toBool()); } else if (vtype == QVariant::Double || vtype == QVariant::Int || vtype == QVariant::UInt || vtype == QVariant::LongLong || vtype == QVariant::ULongLong) { - return QScriptValue(val.toDouble()); + return QJSValue(val.toDouble()); } else { - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } } // ---------------------------------------------------------------------- // Parse ini-style config file, // returning content as hash of hashes by group and key. // Parsing is not fussy, it will read what it can. TsConfig readConfig(const QString &fname) { TsConfig config; // Add empty group. TsConfig::iterator configGroup; configGroup = config.insert(QString(), TsConfigGroup()); QFile file(fname); if (!file.open(QIODevice::ReadOnly)) { return config; } QTextStream stream(&file); stream.setCodec("UTF-8"); while (!stream.atEnd()) { QString line = stream.readLine(); int p1, p2; // Remove comment from the line. p1 = line.indexOf(QLatin1Char('#')); if (p1 >= 0) { line.truncate(p1); } line = line.trimmed(); if (line.isEmpty()) { continue; } if (line[0] == QLatin1Char('[')) { // Group switch. p1 = 0; p2 = line.indexOf(QLatin1Char(']'), p1 + 1); if (p2 < 0) { continue; } QString group = line.mid(p1 + 1, p2 - p1 - 1).trimmed(); configGroup = config.find(group); if (configGroup == config.end()) { // Add new group. configGroup = config.insert(group, TsConfigGroup()); } } else { // Field. p1 = line.indexOf(QLatin1Char('=')); if (p1 < 0) { continue; } QStringRef field = line.leftRef(p1).trimmed(); QStringRef value = line.midRef(p1 + 1).trimmed(); if (!field.isEmpty()) { (*configGroup)[field.toString()] = value.toString(); } } } file.close(); return config; } // ---------------------------------------------------------------------- // throw or log error, depending on context availability -static QScriptValue throwError(QScriptContext *context, QScriptContext::Error errorCode, const QString &message) +static QJSValue throwError(QJSEngine *engine, const QString &message) { - if (context) { - return context->throwError(errorCode, message); + if (engine) { + return engine->evaluate(QStringLiteral("new Error(%1)").arg(message)); } - qCritical() << "Script error" << errorCode << ":" << message; - return QScriptValue::UndefinedValue; + qCritical() << "Script error" << message; + return QJSValue::UndefinedValue; } -// ---------------------------------------------------------------------- -// convert variable number of call arguments to QScriptValueList -static QScriptValueList callArgsFromContext(QScriptContext *context) -{ - QScriptValueList list; - - if (context) { - list.reserve(context->argumentCount()); - for (int i = 0; i < context->argumentCount(); ++i) { - list << context->argument(i); - } - } - - return list; -} - - #ifdef KTRANSCRIPT_TESTBUILD // ---------------------------------------------------------------------- // Test build creation/destruction hooks static KTranscriptImp *s_transcriptInstance = nullptr; KTranscriptImp *globalKTI() { return s_transcriptInstance; } KTranscript *autotestCreateKTranscriptImp() { Q_ASSERT(s_transcriptInstance == nullptr); s_transcriptInstance = new KTranscriptImp; return s_transcriptInstance; } void autotestDestroyKTranscriptImp() { Q_ASSERT(s_transcriptInstance != nullptr); delete s_transcriptInstance; s_transcriptInstance = nullptr; } #else // ---------------------------------------------------------------------- // Dynamic loading. Q_GLOBAL_STATIC(KTranscriptImp, globalKTI) extern "C" { KTRANSCRIPT_EXPORT KTranscript *load_transcript() { return globalKTI(); } } #endif // ---------------------------------------------------------------------- // KTranscript definitions. KTranscriptImp::KTranscriptImp() { // Load user configuration. QString tsConfigPath = QStandardPaths::locate(QStandardPaths::ConfigLocation, QStringLiteral("ktranscript.ini")); if (tsConfigPath.isEmpty()) { tsConfigPath = QDir::homePath() + QLatin1Char('/') + QLatin1String(".transcriptrc"); } config = readConfig(tsConfigPath); } KTranscriptImp::~KTranscriptImp() { qDeleteAll(m_sface); } QString KTranscriptImp::eval(const QList &argv, const QString &lang, const QString &ctry, const QString &msgctxt, const QHash &dynctxt, const QString &msgid, const QStringList &subs, const QList &vals, const QString &ftrans, QList &mods, QString &error, bool &fallback) { //error = "debug"; return QString(); error.clear(); // empty error message means successful evaluation fallback = false; // fallback not requested #if 0 - // FIXME: Maybe not needed, as QScriptEngine has no native outside access? + // FIXME: Maybe not needed, as QJSEngine has no native outside access? // Unportable (needs unistd.h)? // If effective user id is root and real user id is not root. if (geteuid() == 0 && getuid() != 0) { // Since scripts are user input, and the program is running with // root permissions while real user is not root, do not invoke // scripting at all, to prevent exploits. error = "Security block: trying to execute a script in suid environment."; return QString(); } #endif // Load any new modules and clear the list. if (!mods.isEmpty()) { loadModules(mods, error); mods.clear(); if (!error.isEmpty()) { return QString(); } } // Add interpreters for new languages. // (though it should never happen here, but earlier when loading modules; // this also means there are no calls set, so the unregistered call error // below will be reported). if (!m_sface.contains(lang)) { setupInterpreter(lang); } // Shortcuts. Scriptface *sface = m_sface[lang]; - QScriptEngine *engine = sface->scriptEngine; - QScriptValue gobj = engine->globalObject(); + QJSEngine *engine = sface->scriptEngine; + QJSValue gobj = engine->globalObject(); // Link current message data for script-side interface. sface->msgcontext = &msgctxt; sface->dyncontext = &dynctxt; sface->msgId = &msgid; sface->subList = &subs; sface->valList = &vals; sface->ftrans = &ftrans; sface->fallbackRequest = &fallback; sface->ctry = &ctry; // Find corresponding JS function. int argc = argv.size(); if (argc < 1) { //error = "At least the call name must be supplied."; // Empty interpolation is OK, possibly used just to initialize // at a given point (e.g. for Ts.setForall() to start having effect). return QString(); } QString funcName = argv[0].toString(); if (!sface->funcs.contains(funcName)) { error = QStringLiteral("Unregistered call to '%1'.").arg(funcName); return QString(); } - QScriptValue func = sface->funcs[funcName]; - QScriptValue fval = sface->fvals[funcName]; + QJSValue func = sface->funcs[funcName]; + QJSValue fval = sface->fvals[funcName]; // Recover module path from the time of definition of this call, // for possible load calls. currentModulePath = sface->fpaths[funcName]; // Execute function. - QScriptValueList arglist; + QJSValueList arglist; arglist.reserve(argc-1); for (int i = 1; i < argc; ++i) { - arglist.append(variantToJsValue(argv[i])); + arglist.append(engine->toScriptValue(argv[i])); } - QScriptValue val; + QJSValue val; if (fval.isObject()) { - val = func.call(fval.toObject(), arglist); + val = func.callWithInstance(fval, arglist); } else { // no object associated to this function, use global - val = func.call(gobj, arglist); + val = func.callWithInstance(gobj, arglist); } if (fallback) { // Fallback to ordinary translation requested. - - // Possibly clear exception state. - if (engine->hasUncaughtException()) { - engine->clearExceptions(); - } - return QString(); - } else if (!engine->hasUncaughtException()) { + } else if (!val.isError()) { // Evaluation successful. if (val.isString()) { // Good to go. return val.toString(); } else { // Accept only strings. QString strval = val.toString(); error = QStringLiteral("Non-string return value: %1").arg(strval); return QString(); } } else { // Exception raised. - error = expt2str(engine); - - engine->clearExceptions(); + error = expt2str(val); return QString(); } } QStringList KTranscriptImp::postCalls(const QString &lang) { // Return no calls if scripting was not already set up for this language. // NOTE: This shouldn't happen, as postCalls cannot be called in such case. if (!m_sface.contains(lang)) { return QStringList(); } // Shortcuts. Scriptface *sface = m_sface[lang]; return sface->nameForalls; } void KTranscriptImp::loadModules(const QList &mods, QString &error) { QList modErrors; foreach (const QStringList &mod, mods) { QString mpath = mod[0]; QString mlang = mod[1]; // Add interpreters for new languages. if (!m_sface.contains(mlang)) { setupInterpreter(mlang); } // Setup current module path for loading submodules. // (sort of closure over invocations of loadf) int posls = mpath.lastIndexOf(QLatin1Char('/')); if (posls < 1) { modErrors.append(QStringLiteral( "Funny module path '%1', skipping.").arg(mpath)); continue; } currentModulePath = mpath.left(posls); QString fname = mpath.mid(posls + 1); // Scriptface::loadf() wants no extension on the filename fname = fname.left(fname.lastIndexOf(QLatin1Char('.'))); // Load the module. - QScriptEngine *engine = m_sface[mlang]->scriptEngine; - QScriptValueList alist; - alist.append(QScriptValue(fname)); + QJSValueList alist; + alist.append(QJSValue(fname)); m_sface[mlang]->load(alist); - - // Handle any exception. - if (engine->hasUncaughtException()) { - modErrors.append(expt2str(engine)); - engine->clearExceptions(); - } } // Unset module path. currentModulePath.clear(); foreach (const QString &merr, modErrors) { error.append(merr + QLatin1Char('\n')); } } #define SFNAME "Ts" void KTranscriptImp::setupInterpreter(const QString &lang) { // Add scripting interface // Creates its own script engine and registers with it // NOTE: Config may not contain an entry for the language, in which case // it is automatically constructed as an empty hash. This is intended. Scriptface *sface = new Scriptface(config[lang]); // Store scriptface m_sface[lang] = sface; //dbgout("=====> Created interpreter for '%1'", lang); } Scriptface::Scriptface(const TsConfigGroup &config_, QObject *parent) - : QObject(parent), scriptEngine(new QScriptEngine(this)), fallbackRequest(nullptr), config(config_) + : QObject(parent), scriptEngine(new QJSEngine), fallbackRequest(nullptr), config(config_) { - QScriptEngine::QObjectWrapOptions wrapOptions; - wrapOptions |= QScriptEngine::ExcludeSuperClassContents; - wrapOptions |= QScriptEngine::ExcludeDeleteLater; - wrapOptions |= QScriptEngine::ExcludeChildObjects; - wrapOptions |= QScriptEngine::ExcludeSlots; - - QScriptValue object = scriptEngine->newQObject(this, QScriptEngine::QtOwnership, wrapOptions); + QJSValue object = scriptEngine->newQObject(this); scriptEngine->globalObject().setProperty(QStringLiteral(SFNAME), object); + scriptEngine->evaluate(QStringLiteral("Ts.acall = function() { return Ts.acallInternal(Array.prototype.slice.call(arguments)); };")); } Scriptface::~Scriptface() { qDeleteAll(loadedPmapHandles); + scriptEngine->deleteLater(); } -void Scriptface::put(const QString &propertyName, const QScriptValue &value) +void Scriptface::put(const QString &propertyName, const QJSValue &value) { - QScriptValue internalObject = scriptEngine->globalObject().property(QStringLiteral("ScriptfaceInternal")); - if (!internalObject.isValid()) { + QJSValue internalObject = scriptEngine->globalObject().property(QStringLiteral("ScriptfaceInternal")); + if (internalObject.isUndefined()) { internalObject = scriptEngine->newObject(); scriptEngine->globalObject().setProperty(QStringLiteral("ScriptfaceInternal"), internalObject); } internalObject.setProperty(propertyName, value); } // ---------------------------------------------------------------------- // Scriptface interface functions. #ifdef _MSC_VER // Work around bizarre MSVC (2013) bug preventing use of QStringLiteral for concatenated string literals # define SPREF(X) QString::fromLatin1(SFNAME "." X) #else # define SPREF(X) QStringLiteral(SFNAME "." X) #endif -QScriptValue Scriptface::load() +QJSValue Scriptface::load(const QString &name) { - const QScriptValueList fnames = callArgsFromContext(context()); + QJSValueList fnames; + fnames << name; return load(fnames); } -QScriptValue Scriptface::setcall(const QScriptValue &name, const QScriptValue &func, const QScriptValue &fval) +QJSValue Scriptface::setcall(const QJSValue &name, const QJSValue &func, const QJSValue &fval) { if (!name.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setcall: expected string as first argument")); } - if (!func.isFunction()) { - return throwError(context(), QScriptContext::TypeError, + if (!func.isCallable()) { + return throwError(scriptEngine, SPREF("setcall: expected function as second argument")); } if (!(fval.isObject() || fval.isNull())) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setcall: expected object or null as third argument")); } QString qname = name.toString(); funcs[qname] = func; fvals[qname] = fval; // Register values to keep GC from collecting them. Is this needed? put(QStringLiteral("#:f<%1>").arg(qname), func); put(QStringLiteral("#:o<%1>").arg(qname), fval); // Set current module path as module path for this call, // in case it contains load subcalls. fpaths[qname] = globalKTI()->currentModulePath; - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } -QScriptValue Scriptface::hascall(const QScriptValue &name) +QJSValue Scriptface::hascall(const QString &qname) { - if (!name.isString()) { - return throwError(context(), QScriptContext::TypeError, - SPREF("hascall: expected string as first argument")); - } - - QString qname = name.toString(); - return QScriptValue(funcs.contains(qname)); + return QJSValue(funcs.contains(qname)); } -QScriptValue Scriptface::acall() +QJSValue Scriptface::acallInternal(const QJSValue &args) { - const QScriptValueList argv = callArgsFromContext(context()); + QJSValueIterator it(args); - if (argv.size() < 1) { - return throwError(context(), QScriptContext::SyntaxError, + if (!it.next()) { + return throwError(scriptEngine, SPREF("acall: expected at least one argument (call name)")); } - if (!argv[0].isString()) { - return throwError(context(), QScriptContext::SyntaxError, + if (!it.value().isString()) { + return throwError(scriptEngine, SPREF("acall: expected string as first argument (call name)")); } - // Get the function and its context object. - QString callname = argv[0].toString(); + QString callname = it.value().toString(); if (!funcs.contains(callname)) { - return throwError(context(), QScriptContext::ReferenceError, + return throwError(scriptEngine, SPREF("acall: unregistered call to '%1'").arg(callname)); } - QScriptValue func = funcs[callname]; - QScriptValue fval = fvals[callname]; + QJSValue func = funcs[callname]; + QJSValue fval = fvals[callname]; // Recover module path from the time of definition of this call, // for possible load calls. globalKTI()->currentModulePath = fpaths[callname]; // Execute function. - QScriptValueList arglist; - arglist.reserve(argv.size()-1); - for (int i = 1; i < argv.size(); ++i) { - arglist.append(argv[i]); - } - QScriptValue val; + QJSValueList arglist; + while (it.next()) + arglist.append(it.value()); + + QJSValue val; if (fval.isObject()) { // Call function with the context object. - val = func.call(fval.toObject(), arglist); + val = func.callWithInstance(fval, arglist); } else { // No context object associated to this function, use global. - val = func.call(scriptEngine->globalObject(), arglist); + val = func.callWithInstance(scriptEngine->globalObject(), arglist); } return val; } -QScriptValue Scriptface::setcallForall(const QScriptValue &name, const QScriptValue &func, const QScriptValue &fval) +QJSValue Scriptface::setcallForall(const QJSValue &name, const QJSValue &func, const QJSValue &fval) { if (!name.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setcallForall: expected string as first argument")); } - if (!func.isFunction()) { - return throwError(context(), QScriptContext::TypeError, + if (!func.isCallable()) { + return throwError(scriptEngine, SPREF("setcallForall: expected function as second argument")); } if (!(fval.isObject() || fval.isNull())) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setcallForall: expected object or null as third argument")); } QString qname = name.toString(); funcs[qname] = func; fvals[qname] = fval; // Register values to keep GC from collecting them. Is this needed? put(QStringLiteral("#:fall<%1>").arg(qname), func); put(QStringLiteral("#:oall<%1>").arg(qname), fval); // Set current module path as module path for this call, // in case it contains load subcalls. fpaths[qname] = globalKTI()->currentModulePath; // Put in the queue order for execution on all messages. nameForalls.append(qname); - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } -QScriptValue Scriptface::fallback() +QJSValue Scriptface::fallback() { if (fallbackRequest) { *fallbackRequest = true; } - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } -QScriptValue Scriptface::nsubs() +QJSValue Scriptface::nsubs() { - return QScriptValue(subList->size()); + return QJSValue(subList->size()); } -QScriptValue Scriptface::subs(const QScriptValue &index) +QJSValue Scriptface::subs(const QJSValue &index) { if (!index.isNumber()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("subs: expected number as first argument")); } int i = qRound(index.toNumber()); if (i < 0 || i >= subList->size()) { - return throwError(context(), QScriptContext::RangeError, + return throwError(scriptEngine, SPREF("subs: index out of range")); } - return QScriptValue(subList->at(i)); + return QJSValue(subList->at(i)); } -QScriptValue Scriptface::vals(const QScriptValue &index) +QJSValue Scriptface::vals(const QJSValue &index) { if (!index.isNumber()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("vals: expected number as first argument")); } int i = qRound(index.toNumber()); if (i < 0 || i >= valList->size()) { - return throwError(context(), QScriptContext::RangeError, + return throwError(scriptEngine, SPREF("vals: index out of range")); } - return variantToJsValue(valList->at(i)); + return scriptEngine->toScriptValue(valList->at(i)); +// return variantToJsValue(valList->at(i)); } -QScriptValue Scriptface::msgctxt() +QJSValue Scriptface::msgctxt() { - return QScriptValue(*msgcontext); + return QJSValue(*msgcontext); } -QScriptValue Scriptface::dynctxt(const QScriptValue &key) +QJSValue Scriptface::dynctxt(const QString &qkey) { - if (!key.isString()) { - return throwError(context(), QScriptContext::TypeError, - SPREF("dynctxt: expected string as first argument")); - } - - QString qkey = key.toString(); if (dyncontext->contains(qkey)) { - return QScriptValue(dyncontext->value(qkey)); + return QJSValue(dyncontext->value(qkey)); } - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } -QScriptValue Scriptface::msgid() +QJSValue Scriptface::msgid() { - return QScriptValue(*msgId); + return QJSValue(*msgId); } -QScriptValue Scriptface::msgkey() +QJSValue Scriptface::msgkey() { - return QScriptValue(QString(*msgcontext + QLatin1Char('|') + *msgId)); + return QJSValue(QString(*msgcontext + QLatin1Char('|') + *msgId)); } -QScriptValue Scriptface::msgstrf() +QJSValue Scriptface::msgstrf() { - return QScriptValue(*ftrans); + return QJSValue(*ftrans); } -QScriptValue Scriptface::dbgputs(const QScriptValue &str) +void Scriptface::dbgputs(const QString &qstr) { - if (!str.isString()) { - return throwError(context(), QScriptContext::TypeError, - SPREF("dbgputs: expected string as first argument")); - } - - QString qstr = str.toString(); - dbgout("[JS-debug] %1", qstr); - - return QScriptValue::UndefinedValue; } -QScriptValue Scriptface::warnputs(const QScriptValue &str) +void Scriptface::warnputs(const QString &qstr) { - if (!str.isString()) { - return throwError(context(), QScriptContext::TypeError, - SPREF("warnputs: expected string as first argument")); - } - - QString qstr = str.toString(); - warnout("[JS-warning] %1", qstr); - - return QScriptValue::UndefinedValue; } -QScriptValue Scriptface::localeCountry() +QJSValue Scriptface::localeCountry() { - return QScriptValue(*ctry); + return QJSValue(*ctry); } -QScriptValue Scriptface::normKey(const QScriptValue &phrase) +QJSValue Scriptface::normKey(const QJSValue &phrase) { if (!phrase.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("normKey: expected string as argument")); } QByteArray nqphrase = normKeystr(phrase.toString()); - return QScriptValue(QString::fromUtf8(nqphrase)); + return QJSValue(QString::fromUtf8(nqphrase)); } -QScriptValue Scriptface::loadProps() +QJSValue Scriptface::loadProps(const QString &name) { - const QScriptValueList fnames = callArgsFromContext(context()); + QJSValueList fnames; + fnames << name; + return loadProps(fnames); +} +QJSValue Scriptface::loadProps(const QJSValueList &fnames) +{ if (globalKTI()->currentModulePath.isEmpty()) { - return throwError(context(), QScriptContext::UnknownError, + return throwError(scriptEngine, SPREF("loadProps: no current module path, aiiie...")); } for (int i = 0; i < fnames.size(); ++i) { if (!fnames[i].isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("loadProps: expected string as file name")); } } for (int i = 0; i < fnames.size(); ++i) { QString qfname = fnames[i].toString(); QString qfpath_base = globalKTI()->currentModulePath + QLatin1Char('/') + qfname; // Determine which kind of map is available. // Give preference to compiled map. QString qfpath = qfpath_base + QLatin1String(".pmapc"); bool haveCompiled = true; QFile file_check(qfpath); if (!file_check.open(QIODevice::ReadOnly)) { haveCompiled = false; qfpath = qfpath_base + QLatin1String(".pmap"); QFile file_check(qfpath); if (!file_check.open(QIODevice::ReadOnly)) { - return throwError(context(), QScriptContext::UnknownError, + return throwError(scriptEngine, SPREF("loadProps: cannot read map '%1'") .arg(qfpath)); } } file_check.close(); // Load from appropriate type of map. if (!loadedPmapPaths.contains(qfpath)) { QString errorString; if (haveCompiled) { errorString = loadProps_bin(qfpath); } else { errorString = loadProps_text(qfpath); } if (!errorString.isEmpty()) { - return throwError(context(), QScriptContext::SyntaxError, errorString); + return throwError(scriptEngine, errorString); } dbgout("Loaded property map: %1", qfpath); loadedPmapPaths.insert(qfpath); } } - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } -QScriptValue Scriptface::getProp(const QScriptValue &phrase, const QScriptValue &prop) +QJSValue Scriptface::getProp(const QJSValue &phrase, const QJSValue &prop) { if (!phrase.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("getProp: expected string as first argument")); } if (!prop.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("getProp: expected string as second argument")); } QByteArray qphrase = normKeystr(phrase.toString()); QHash props = phraseProps.value(qphrase); if (props.isEmpty()) { props = resolveUnparsedProps(qphrase); } if (!props.isEmpty()) { QByteArray qprop = normKeystr(prop.toString()); QByteArray qval = props.value(qprop); if (!qval.isEmpty()) { - return QScriptValue(QString::fromUtf8(qval)); + return QJSValue(QString::fromUtf8(qval)); } } - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } -QScriptValue Scriptface::setProp(const QScriptValue &phrase, const QScriptValue &prop, const QScriptValue &value) +QJSValue Scriptface::setProp(const QJSValue &phrase, const QJSValue &prop, const QJSValue &value) { if (!phrase.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setProp: expected string as first argument")); } if (!prop.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setProp: expected string as second argument")); } if (!value.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("setProp: expected string as third argument")); } QByteArray qphrase = normKeystr(phrase.toString()); QByteArray qprop = normKeystr(prop.toString()); QByteArray qvalue = value.toString().toUtf8(); // Any non-existent key in first or second-level hash will be created. phraseProps[qphrase][qprop] = qvalue; - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } static QString toCaseFirst(const QString &qstr, int qnalt, bool toupper) { static const QLatin1String head("~@"); static const int hlen = 2; //head.length() // If the first letter is found within an alternatives directive, // change case of the first letter in each of the alternatives. QString qstrcc = qstr; int len = qstr.length(); QChar altSep; int remainingAlts = 0; bool checkCase = true; int numChcased = 0; int i = 0; while (i < len) { QChar c = qstr[i]; if (qnalt && !remainingAlts && qstr.midRef(i, hlen) == head) { // An alternatives directive is just starting. i += 2; if (i >= len) { break; // malformed directive, bail out } // Record alternatives separator, set number of remaining // alternatives, reactivate case checking. altSep = qstrcc[i]; remainingAlts = qnalt; checkCase = true; } else if (remainingAlts && c == altSep) { // Alternative separator found, reduce number of remaining // alternatives and reactivate case checking. --remainingAlts; checkCase = true; } else if (checkCase && c.isLetter()) { // Case check is active and the character is a letter; change case. if (toupper) { qstrcc[i] = c.toUpper(); } else { qstrcc[i] = c.toLower(); } ++numChcased; // No more case checks until next alternatives separator. checkCase = false; } // If any letter has been changed, and there are no more alternatives // to be processed, we're done. if (numChcased > 0 && remainingAlts == 0) { break; } // Go to next character. ++i; } return qstrcc; } -QScriptValue Scriptface::toUpperFirst(const QScriptValue &str, const QScriptValue &nalt) +QJSValue Scriptface::toUpperFirst(const QJSValue &str, const QJSValue &nalt) { if (!str.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("toUpperFirst: expected string as first argument")); } if (!(nalt.isNumber() || nalt.isNull())) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("toUpperFirst: expected number as second argument")); } QString qstr = str.toString(); - int qnalt = nalt.isNull() ? 0 : nalt.toInteger(); + int qnalt = nalt.isNull() ? 0 : nalt.toInt(); QString qstruc = toCaseFirst(qstr, qnalt, true); - return QScriptValue(qstruc); + return QJSValue(qstruc); } -QScriptValue Scriptface::toLowerFirst(const QScriptValue &str, const QScriptValue &nalt) +QJSValue Scriptface::toLowerFirst(const QJSValue &str, const QJSValue &nalt) { if (!str.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("toLowerFirst: expected string as first argument")); } if (!(nalt.isNumber() || nalt.isNull())) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("toLowerFirst: expected number as second argument")); } QString qstr = str.toString(); - int qnalt = nalt.isNull() ? 0 : nalt.toInteger(); + int qnalt = nalt.isNull() ? 0 : nalt.toInt(); QString qstrlc = toCaseFirst(qstr, qnalt, false); - return QScriptValue(qstrlc); + return QJSValue(qstrlc); } -QScriptValue Scriptface::getConfString(const QScriptValue &key, const QScriptValue &dval) +QJSValue Scriptface::getConfString(const QJSValue &key, const QJSValue &dval) { if (!key.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, QStringLiteral("getConfString: expected string as first argument")); } if (!(dval.isString() || dval.isNull())) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("getConfString: expected string as second argument (when given)")); } QString qkey = key.toString(); if (config.contains(qkey)) { - return QScriptValue(config.value(qkey)); + return QJSValue(config.value(qkey)); } - return dval.isNull() ? QScriptValue::UndefinedValue : dval; + return dval.isNull() ? QJSValue::UndefinedValue : dval; } -QScriptValue Scriptface::getConfBool(const QScriptValue &key, const QScriptValue &dval) +QJSValue Scriptface::getConfBool(const QJSValue &key, const QJSValue &dval) { if (!key.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("getConfBool: expected string as first argument")); } - if (!(dval.isBoolean() || dval.isNull())) { - return throwError(context(), QScriptContext::TypeError, + if (!(dval.isBool() || dval.isNull())) { + return throwError(scriptEngine, SPREF("getConfBool: expected boolean as second argument (when given)")); } static QStringList falsities; if (falsities.isEmpty()) { falsities.append(QString(QLatin1Char('0'))); falsities.append(QStringLiteral("no")); falsities.append(QStringLiteral("false")); } QString qkey = key.toString(); if (config.contains(qkey)) { QString qval = config.value(qkey).toLower(); - return QScriptValue(!falsities.contains(qval)); + return QJSValue(!falsities.contains(qval)); } - return dval.isNull() ? QScriptValue::UndefinedValue : dval; + return dval.isNull() ? QJSValue::UndefinedValue : dval; } -QScriptValue Scriptface::getConfNumber(const QScriptValue &key, const QScriptValue &dval) +QJSValue Scriptface::getConfNumber(const QJSValue &key, const QJSValue &dval) { if (!key.isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("getConfNumber: expected string " "as first argument")); } if (!(dval.isNumber() || dval.isNull())) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("getConfNumber: expected number " "as second argument (when given)")); } QString qkey = key.toString(); if (config.contains(qkey)) { QString qval = config.value(qkey); bool convOk; double qnum = qval.toDouble(&convOk); if (convOk) { - return QScriptValue(qnum); + return QJSValue(qnum); } } - return dval.isNull() ? QScriptValue::UndefinedValue : dval; + return dval.isNull() ? QJSValue::UndefinedValue : dval; } // ---------------------------------------------------------------------- // Scriptface helpers to interface functions. -QScriptValue Scriptface::load(const QScriptValueList &fnames) +QJSValue Scriptface::load(const QJSValueList &fnames) { if (globalKTI()->currentModulePath.isEmpty()) { - return throwError(context(), QScriptContext::UnknownError, + return throwError(scriptEngine, SPREF("load: no current module path, aiiie...")); } for (int i = 0; i < fnames.size(); ++i) { if (!fnames[i].isString()) { - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, SPREF("load: expected string as file name")); } } for (int i = 0; i < fnames.size(); ++i) { QString qfname = fnames[i].toString(); QString qfpath = globalKTI()->currentModulePath + QLatin1Char('/') + qfname + QLatin1String(".js"); QFile file(qfpath); if (!file.open(QIODevice::ReadOnly)) { - return throwError(context(), QScriptContext::UnknownError, + return throwError(scriptEngine, SPREF("load: cannot read file '%1'") \ .arg(qfpath)); } QTextStream stream(&file); stream.setCodec("UTF-8"); QString source = stream.readAll(); file.close(); - /** - * fixup QScriptContext - * else the nested evaluate will not work :/ - * see http://www.qtcentre.org/threads/31027-QtScript-nesting-with-include-imports-or-spawned-script-engines - * http://www.qtcentre.org/threads/20432-Can-I-include-a-script-from-script - */ - QScriptContext *currentContext = scriptEngine->currentContext(); - QScriptContext *parentContext = currentContext->parentContext(); - if (parentContext) { - currentContext->setActivationObject(currentContext->parentContext()->activationObject()); - currentContext->setThisObject(currentContext->parentContext()->thisObject()); - } - - QScriptValue comp = scriptEngine->evaluate(source, qfpath, 0); + QJSValue comp = scriptEngine->evaluate(source, qfpath, 0); if (comp.isError()) { QString msg = comp.toString(); QString line; if (comp.isObject()) { - QScriptValue lval = comp.toObject().property(QStringLiteral("line")); + QJSValue lval = comp.property(QStringLiteral("line")); if (lval.isNumber()) { - line = QString::number(lval.toInt32()); + line = QString::number(lval.toInt()); } } - return throwError(context(), QScriptContext::TypeError, + return throwError(scriptEngine, QStringLiteral("at %1:%2: %3") .arg(qfpath, line, msg)); } dbgout("Loaded module: %1", qfpath); } - return QScriptValue::UndefinedValue; + return QJSValue::UndefinedValue; } QString Scriptface::loadProps_text(const QString &fpath) { QFile file(fpath); if (!file.open(QIODevice::ReadOnly)) { return SPREF("loadProps_text: cannot read file '%1'") .arg(fpath); } QTextStream stream(&file); stream.setCodec("UTF-8"); QString s = stream.readAll(); file.close(); // Parse the map. // Should care about performance: possibly executed on each KDE // app startup and reading houndreds of thousands of characters. enum {s_nextEntry, s_nextKey, s_nextValue}; QList ekeys; // holds keys for current entry QHash props; // holds properties for current entry int slen = s.length(); int state = s_nextEntry; QByteArray pkey; QChar prop_sep, key_sep; int i = 0; while (1) { int i_checkpoint = i; if (state == s_nextEntry) { while (s[i].isSpace()) { ++i; if (i >= slen) { goto END_PROP_PARSE; } } if (i + 1 >= slen) { return SPREF("loadProps_text: unexpected end " "of file in %1").arg(fpath); } if (s[i] != QLatin1Char('#')) { // Separator characters for this entry. key_sep = s[i]; prop_sep = s[i + 1]; if (key_sep.isLetter() || prop_sep.isLetter()) { return SPREF("loadProps_text: separator " "characters must not be letters at %1:%2") .arg(fpath).arg(countLines(s, i)); } // Reset all data for current entry. ekeys.clear(); props.clear(); pkey.clear(); i += 2; state = s_nextKey; } else { // This is a comment, skip to EOL, don't change state. while (s[i] != QLatin1Char('\n')) { ++i; if (i >= slen) { goto END_PROP_PARSE; } } } } else if (state == s_nextKey) { int ip = i; // Proceed up to next key or property separator. while (s[i] != key_sep && s[i] != prop_sep) { ++i; if (i >= slen) { goto END_PROP_PARSE; } } if (s[i] == key_sep) { // This is a property key, // record for when the value gets parsed. pkey = normKeystr(s.mid(ip, i - ip), false); i += 1; state = s_nextValue; } else { // if (s[i] == prop_sep) { // This is an entry key, or end of entry. QByteArray ekey = normKeystr(s.mid(ip, i - ip), false); if (!ekey.isEmpty()) { // An entry key. ekeys.append(ekey); i += 1; state = s_nextKey; } else { // End of entry. if (ekeys.size() < 1) { return SPREF("loadProps_text: no entry key " "for entry ending at %1:%2") .arg(fpath).arg(countLines(s, i)); } // Add collected entry into global store, // once for each entry key (QHash implicitly shared). foreach (const QByteArray &ekey, ekeys) { phraseProps[ekey] = props; } i += 1; state = s_nextEntry; } } } else if (state == s_nextValue) { int ip = i; // Proceed up to next property separator. while (s[i] != prop_sep) { ++i; if (i >= slen) { goto END_PROP_PARSE; } if (s[i] == key_sep) { return SPREF("loadProps_text: property separator " "inside property value at %1:%2") .arg(fpath).arg(countLines(s, i)); } } // Extract the property value and store the property. QByteArray pval = trimSmart(s.mid(ip, i - ip)).toUtf8(); props[pkey] = pval; i += 1; state = s_nextKey; } else { return SPREF("loadProps: internal error 10 at %1:%2") .arg(fpath).arg(countLines(s, i)); } // To avoid infinite looping and stepping out. if (i == i_checkpoint || i >= slen) { return SPREF("loadProps: internal error 20 at %1:%2") .arg(fpath).arg(countLines(s, i)); } } END_PROP_PARSE: if (state != s_nextEntry) { return SPREF("loadProps: unexpected end of file in %1") .arg(fpath); } return QString(); } // Read big-endian integer of nbytes length at position pos // in character array fc of length len. // Update position to point after the number. // In case of error, pos is set to -1. template static int bin_read_int_nbytes(const char *fc, qlonglong len, qlonglong &pos, int nbytes) { if (pos + nbytes > len) { pos = -1; return 0; } T num = qFromBigEndian((uchar *) fc + pos); pos += nbytes; return num; } // Read 64-bit big-endian integer. static quint64 bin_read_int64(const char *fc, qlonglong len, qlonglong &pos) { return bin_read_int_nbytes(fc, len, pos, 8); } // Read 32-bit big-endian integer. static quint32 bin_read_int(const char *fc, qlonglong len, qlonglong &pos) { return bin_read_int_nbytes(fc, len, pos, 4); } // Read string at position pos of character array fc of length n. // String is represented as 32-bit big-endian byte length followed by bytes. // Update position to point after the string. // In case of error, pos is set to -1. static QByteArray bin_read_string(const char *fc, qlonglong len, qlonglong &pos) { // Binary format stores strings as length followed by byte sequence. // No null-termination. int nbytes = bin_read_int(fc, len, pos); if (pos < 0) { return QByteArray(); } if (nbytes < 0 || pos + nbytes > len) { pos = -1; return QByteArray(); } QByteArray s(fc + pos, nbytes); pos += nbytes; return s; } QString Scriptface::loadProps_bin(const QString &fpath) { QFile file(fpath); if (!file.open(QIODevice::ReadOnly)) { return SPREF("loadProps: cannot read file '%1'") .arg(fpath); } // Collect header. QByteArray head(8, '0'); file.read(head.data(), head.size()); file.close(); // Choose pmap loader based on header. if (head == "TSPMAP00") { return loadProps_bin_00(fpath); } else if (head == "TSPMAP01") { return loadProps_bin_01(fpath); } else { return SPREF("loadProps: unknown version of compiled map '%1'") .arg(fpath); } } QString Scriptface::loadProps_bin_00(const QString &fpath) { QFile file(fpath); if (!file.open(QIODevice::ReadOnly)) { return SPREF("loadProps: cannot read file '%1'") .arg(fpath); } QByteArray fctmp = file.readAll(); file.close(); const char *fc = fctmp.data(); const int fclen = fctmp.size(); // Indicates stream state. qlonglong pos = 0; // Match header. QByteArray head(fc, 8); pos += 8; if (head != "TSPMAP00") { goto END_PROP_PARSE; } // Read total number of entries. int nentries; nentries = bin_read_int(fc, fclen, pos); if (pos < 0) { goto END_PROP_PARSE; } // Read all entries. for (int i = 0; i < nentries; ++i) { // Read number of entry keys and all entry keys. QList ekeys; int nekeys = bin_read_int(fc, fclen, pos); if (pos < 0) { goto END_PROP_PARSE; } ekeys.reserve(nekeys); //nekeys are appended if data is not corrupted for (int j = 0; j < nekeys; ++j) { QByteArray ekey = bin_read_string(fc, fclen, pos); if (pos < 0) { goto END_PROP_PARSE; } ekeys.append(ekey); } //dbgout("--------> ekey[0]={%1}", QString::fromUtf8(ekeys[0])); // Read number of properties and all properties. QHash props; int nprops = bin_read_int(fc, fclen, pos); if (pos < 0) { goto END_PROP_PARSE; } for (int j = 0; j < nprops; ++j) { QByteArray pkey = bin_read_string(fc, fclen, pos); if (pos < 0) { goto END_PROP_PARSE; } QByteArray pval = bin_read_string(fc, fclen, pos); if (pos < 0) { goto END_PROP_PARSE; } props[pkey] = pval; } // Add collected entry into global store, // once for each entry key (QHash implicitly shared). foreach (const QByteArray &ekey, ekeys) { phraseProps[ekey] = props; } } END_PROP_PARSE: if (pos < 0) { return SPREF("loadProps: corrupt compiled map '%1'") .arg(fpath); } return QString(); } QString Scriptface::loadProps_bin_01(const QString &fpath) { QFile *file = new QFile(fpath); if (!file->open(QIODevice::ReadOnly)) { return SPREF("loadProps: cannot read file '%1'") .arg(fpath); } QByteArray fstr; qlonglong pos; // Read the header and number and length of entry keys. fstr = file->read(8 + 4 + 8); pos = 0; QByteArray head = fstr.left(8); pos += 8; if (head != "TSPMAP01") { return SPREF("loadProps: corrupt compiled map '%1'") .arg(fpath); } quint32 numekeys = bin_read_int(fstr, fstr.size(), pos); quint64 lenekeys = bin_read_int64(fstr, fstr.size(), pos); // Read entry keys. fstr = file->read(lenekeys); pos = 0; for (quint32 i = 0; i < numekeys; ++i) { QByteArray ekey = bin_read_string(fstr, lenekeys, pos); quint64 offset = bin_read_int64(fstr, lenekeys, pos); phraseUnparsedProps[ekey] = QPair(file, offset); } // // Read property keys. // ...when it becomes necessary loadedPmapHandles.insert(file); return QString(); } QHash Scriptface::resolveUnparsedProps(const QByteArray &phrase) { QPair ref = phraseUnparsedProps.value(phrase); QFile *file = ref.first; quint64 offset = ref.second; QHash props; if (file && file->seek(offset)) { QByteArray fstr = file->read(4 + 4); qlonglong pos = 0; quint32 numpkeys = bin_read_int(fstr, fstr.size(), pos); quint32 lenpkeys = bin_read_int(fstr, fstr.size(), pos); fstr = file->read(lenpkeys); pos = 0; for (quint32 i = 0; i < numpkeys; ++i) { QByteArray pkey = bin_read_string(fstr, lenpkeys, pos); QByteArray pval = bin_read_string(fstr, lenpkeys, pos); props[pkey] = pval; } phraseProps[phrase] = props; phraseUnparsedProps.remove(phrase); } return props; } #include "ktranscript.moc"