From c0f3e69669537c52d92a8d5845b2f0dd7278f93a Mon Sep 17 00:00:00 2001 From: Elliu <elliu@hashi.re> Date: Wed, 9 Feb 2022 23:47:56 +0100 Subject: [PATCH] WIP: debug --- CMakeLists.txt | 6 - src/Lib/Script/CRTPLuaScriptObject.hh | 381 ------------------ .../CRTPLuaScriptObject/FreeFunctions.cc | 57 --- .../FunctionDeclaration.cc | 69 ---- .../CRTPLuaScriptObject/JobDeclaration.cc | 101 ----- .../CRTPLuaScriptObject/ModuleDeclaration.cc | 262 ------------ .../CRTPLuaScriptObject/OptionDeclaration.cc | 48 --- src/Lib/Script/LuaContext.cc | 297 -------------- src/Lib/Script/LuaContext.hh | 119 ------ src/Lib/Script/ScriptDocument.cc | 56 --- src/Lib/Script/ScriptDocument.hh | 28 -- src/Lib/Script/ScriptOption.cc | 63 --- src/Lib/Script/ScriptOption.hh | 30 -- src/Lib/Script/ScriptStore.cc | 83 ---- src/Lib/Script/ScriptStore.hh | 42 -- src/UI/DocumentViews/MpvWidget.cc | 11 +- src/UI/MainWindow.cc | 25 +- src/UI/MainWindow.hh | 1 - src/UI/ScriptDocumentView.cc | 142 ------- src/UI/ScriptDocumentView.hh | 58 --- src/UI/ScriptViews/EditorProxy.cc | 330 --------------- src/UI/ScriptViews/EditorProxy.hh | 66 --- src/UI/ScriptViews/ScriptEditor.cc | 173 -------- src/UI/ScriptViews/ScriptEditor.hh | 60 --- src/UI/ScriptViews/ScriptHighlighter.cc | 172 -------- src/UI/ScriptViews/ScriptHighlighter.hh | 58 --- src/VivyApplication.cc | 20 +- 27 files changed, 24 insertions(+), 2734 deletions(-) delete mode 100644 src/Lib/Script/CRTPLuaScriptObject.hh delete mode 100644 src/Lib/Script/CRTPLuaScriptObject/FreeFunctions.cc delete mode 100644 src/Lib/Script/CRTPLuaScriptObject/FunctionDeclaration.cc delete mode 100644 src/Lib/Script/CRTPLuaScriptObject/JobDeclaration.cc delete mode 100644 src/Lib/Script/CRTPLuaScriptObject/ModuleDeclaration.cc delete mode 100644 src/Lib/Script/CRTPLuaScriptObject/OptionDeclaration.cc delete mode 100644 src/Lib/Script/LuaContext.cc delete mode 100644 src/Lib/Script/LuaContext.hh delete mode 100644 src/Lib/Script/ScriptDocument.cc delete mode 100644 src/Lib/Script/ScriptDocument.hh delete mode 100644 src/Lib/Script/ScriptOption.cc delete mode 100644 src/Lib/Script/ScriptOption.hh delete mode 100644 src/Lib/Script/ScriptStore.cc delete mode 100644 src/Lib/Script/ScriptStore.hh delete mode 100644 src/UI/ScriptDocumentView.cc delete mode 100644 src/UI/ScriptDocumentView.hh delete mode 100644 src/UI/ScriptViews/EditorProxy.cc delete mode 100644 src/UI/ScriptViews/EditorProxy.hh delete mode 100644 src/UI/ScriptViews/ScriptEditor.cc delete mode 100644 src/UI/ScriptViews/ScriptEditor.hh delete mode 100644 src/UI/ScriptViews/ScriptHighlighter.cc delete mode 100644 src/UI/ScriptViews/ScriptHighlighter.hh diff --git a/CMakeLists.txt b/CMakeLists.txt index c4eea5e7..04f701fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,11 +41,6 @@ find_library(SWRESAMPLE_LIBRARY swresample REQUIRED) find_library(AVFORMAT_LIBRARY avformat REQUIRED) find_library(MPV_LIBRARY mpv REQUIRED) -# Add the lua dependency -add_subdirectory( - "${CMAKE_CURRENT_SOURCE_DIR}/vendor/lua-5.4.3" - "${CMAKE_BINARY_DIR}/vendor/lua-5.4.3" -) # Grab all files file(GLOB_RECURSE Vivy_SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc") @@ -76,7 +71,6 @@ target_link_libraries(Vivy PRIVATE ${AVUTIL_LIBRARY}) target_link_libraries(Vivy PRIVATE ${SWRESAMPLE_LIBRARY}) target_link_libraries(Vivy PRIVATE ${AVFORMAT_LIBRARY}) target_link_libraries(Vivy PRIVATE ${MPV_LIBRARY}) -target_link_libraries(Vivy PRIVATE lua) # Headers related things include("${CMAKE_CURRENT_SOURCE_DIR}/PreCompiledHeaders.cmake") diff --git a/src/Lib/Script/CRTPLuaScriptObject.hh b/src/Lib/Script/CRTPLuaScriptObject.hh deleted file mode 100644 index ac2f3739..00000000 --- a/src/Lib/Script/CRTPLuaScriptObject.hh +++ /dev/null @@ -1,381 +0,0 @@ -#pragma once - -#include "PreCompiledHeaders.hh" -#include "VivyApplication.hh" -#include "Lib/Log.hh" -#include "Lib/Script/LuaContext.hh" -#include "Lib/Script/ScriptOption.hh" - -#include "lua.hpp" - -namespace Vivy::Script -{ -// clang-format off -#define LUA_DECL_METHOD(class, name) luaL_Reg{ #name, class ::name } -#define LUA_DECL_NAMED_METHOD(class, method, name) luaL_Reg{ method, class ::name } -#define LUA_DECL_META_METHOD(class, meta, name) luaL_Reg{ meta, class ::name } -#define LUA_DECL_CREATE(class) luaL_Reg{ "new", class ::CREATE } -#define LUA_RETURN_NOTHING(L) { lua_settop(L, 0); return 0; } -// clang-format on - -#define method_list static constexpr inline auto -#define script_class(theClassName) \ - class theClassName final : public CRTPLuaScriptObject<theClassName> - -#define LUA_DECL_GETTER(type, luaName, value) \ - static int luaName(lua_State *const L) noexcept { return luaPushValue(L, CHECK(L, 1)->value); } - -#define LUA_SCRIPTABLE_CLASS_MANUAL_CTOR(theClassName) \ - VIVY_UNMOVABLE_OBJECT(theClassName) \ - static constexpr char className[] = #theClassName; \ - friend CRTPLuaScriptObject<theClassName>; \ - ~theClassName() noexcept {} - -#define LUA_SCRIPTABLE_CLASS(theClassName) \ - LUA_SCRIPTABLE_CLASS_MANUAL_CTOR(theClassName) \ - theClassName(lua_State *L) noexcept \ - { \ - err(LuaContext::getContext(L)) \ - << "Create instance of " << theClassName::className << "\n"; \ - } - -// The type of the thing that a job iterate over -enum class JobIteratorType { Line = 1, Syllabe = 2 }; - -[[maybe_unused]] static inline JobIteratorType -getJobIteratorTypeFromString(const std::string_view it) noexcept -{ - if (it == "LINE") - return JobIteratorType::Line; - else if (it == "SYLLABE") - return JobIteratorType::Syllabe; - return static_cast<JobIteratorType>(0); // Invalid! -} - -// CRTP to expose objects to Lua -template <class Object> class CRTPLuaScriptObject { -protected: - VIVY_APP_LOGGABLE_OBJECT_BY_STORED_NAME(Object::className, logger) - - [[noreturn]] static void luaGlobalError(lua_State *const L, const std::string &str) noexcept - { - const auto *const context = LuaContext::getContext(L); - lua_pushfstring(L, "%s:0:%s", context->getCurrentLuaFile().c_str(), str.c_str()); - lua_error(L); - exit(EXIT_FAILURE); // lua_error should not return anything - } - - // Push something onto the stack, must be specialized - using std_str = std::string; - using std_strv = std::string_view; - - static int luaPushValue(lua_State *const L, const int &thing) noexcept - { - lua_pushinteger(L, thing); - return 1; - } - - static int luaPushValue(lua_State *const L, const std_strv &thing) noexcept - { - lua_pushlstring(L, thing.data(), thing.size()); - return 1; - } - - static int luaPushValue(lua_State *const L, const std_str &thing) noexcept - { - lua_pushstring(L, thing.c_str()); - return 1; - } - - static bool PushFunctionFromRegistry(lua_State *const L, const int key) noexcept - { - if (key >= 0) { - lua_rawgeti(L, LUA_REGISTRYINDEX, key); - return true; - } else { - lua_pushnil(L); - return false; - } - } - - static void IterateOverArray(lua_State *const L, const int tblIndex, - const auto callback) noexcept - { - luaL_checktype(L, tblIndex, LUA_TTABLE); - const std::size_t count = lua_rawlen(L, tblIndex); - for (int i = 1; std::cmp_less(i, count); ++i) { - luaL_checktype(L, tblIndex, LUA_TTABLE); - lua_pushinteger(L, i); // i -> top stack - lua_gettable(L, tblIndex); // T[i] -> top stack and pop i - - if (lua_type(L, -1) == LUA_TNIL) - break; // Sentinel check - - // If the callback didn't pop the object form the stack, pop - // it ourself. The value will be accessible at the top of the - // stack (index -1). - if (!callback()) - lua_pop(L, -1); - } - } - - static int GC(lua_State *const L) noexcept - { - const Object *const obj = reinterpret_cast<const Object *>(lua_topointer(L, 1)); - auto *context = LuaContext::getContext(L); - out(context) << "Call destructor for " << Object::className; - obj->~Object(); - return 0; - } - - static int TOSTRING(lua_State *const L) noexcept - { - lua_pushfstring(L, "%s { }", Object::className); - return 1; - } - - static int CREATE(lua_State *const L) noexcept - { - lua_settop(L, 0); - Object *const obj = reinterpret_cast<Object *>(lua_newuserdata(L, sizeof(Object))); - new (obj) Object(L); - luaL_getmetatable(L, Object::className); - lua_setmetatable(L, 1); - return 1; - } - - static const std::string_view CHECK_STRING_VIEW(lua_State *const L, int index) noexcept - { - std::size_t len = 0; - const char *const str = luaL_checklstring(L, index, &len); - return std::string_view(str, len); - } - - static inline constexpr luaL_Reg luaRegDefaultGC = { "__gc", GC }; - static inline constexpr luaL_Reg luaRegDefaultTOSTRING = { "__tostring", TOSTRING }; - -public: - static Object *CHECK(lua_State *const L, const int index) noexcept - { - return reinterpret_cast<Object *>(luaL_checkudata(L, index, Object::className)); - } - - static void Register(lua_State *const L) noexcept - { - // Fill the method table, newclass = {} - lua_newtable(L); - const int methodtable = lua_gettop(L); - - // Fill the meta-table, metatable = {} - { - luaL_newmetatable(L, Object::className); - const int metatable = lua_gettop(L); - - lua_pushliteral(L, "__metatable"); - lua_pushvalue(L, methodtable); - lua_settable(L, metatable); - - lua_pushliteral(L, "__index"); - lua_pushvalue(L, methodtable); - lua_settable(L, metatable); - - for (const luaL_Reg &meta : Object::metaMethods) { - lua_pushstring(L, meta.name); - lua_pushcfunction(L, meta.func); - lua_settable(L, metatable); - } - - lua_pop(L, 1); - } - - // Fill the method table with specified methods - for (const luaL_Reg &method : Object::methods) { - lua_pushstring(L, method.name); - lua_pushcfunction(L, method.func); - lua_settable(L, methodtable); - } - - // Last thing to do it seems... - lua_pop(L, 1); // drop method-table - lua_register(L, Object::className, CREATE); // Register the create method - } - -private: - // The user value count - int userValueCount{ 0 }; - -protected: - // Add a user value to this object. Do not used lua_setuservalue or - // lua_setiuservalue directly, use this proxy method. - void addUserValue(lua_State *const L, const int index) noexcept - { - lua_setiuservalue(L, index, ++userValueCount); - } -}; - -// Option declaration -script_class (OptionDeclaration) { - LUA_SCRIPTABLE_CLASS(OptionDeclaration) - - static int addOptionContent(lua_State *const) noexcept; - - static int TOSTRING(lua_State *const) noexcept; - - method_list metaMethods = { - luaRegDefaultGC, - LUA_DECL_META_METHOD(OptionDeclaration, "__tostring", TOSTRING), - }; - method_list methods = { LUA_DECL_METHOD(OptionDeclaration, addOptionContent), - LUA_DECL_CREATE(OptionDeclaration) }; - -public: - // Different option types - std::unordered_map<std::string, ScriptOption> options; -}; - -// Job declaration -script_class (JobDeclaration) { - LUA_SCRIPTABLE_CLASS(JobDeclaration) - - static int setName(lua_State *) noexcept; - static int setOptions(lua_State *) noexcept; - static int setImportFromScript(lua_State *) noexcept; - - static int pushToRuntime(lua_State *const) noexcept; - - static int TOSTRING(lua_State *const) noexcept; - - method_list metaMethods = { luaRegDefaultGC, - LUA_DECL_META_METHOD(JobDeclaration, "__tostring", TOSTRING) }; - method_list methods = { LUA_DECL_METHOD(JobDeclaration, setName), - LUA_DECL_METHOD(JobDeclaration, setOptions), - LUA_DECL_METHOD(JobDeclaration, setImportFromScript), - LUA_DECL_METHOD(JobDeclaration, pushToRuntime), - LUA_DECL_CREATE(JobDeclaration) }; - - bool isImported{ false }; - int functionRegisterKey{ -1 }; - JobIteratorType iterationType{ static_cast<JobIteratorType>(0) }; // Invalid by default - -public: - std::string name{}; - std::string parentScript{}; - std::vector<OptionDeclaration *> options{}; - - bool isLocalToModule() const noexcept; - void pushLuaFunction(lua_State *const) const noexcept; - void getLuaFunctionFromStack(lua_State *const, const JobIteratorType) noexcept; -}; - -// Function declaration -script_class (FunctionDeclaration) { - LUA_SCRIPTABLE_CLASS(FunctionDeclaration) - - static int setName(lua_State *const) noexcept; - static int setImportFromScript(lua_State *const) noexcept; - - static int pushToRuntime(lua_State *const) noexcept; - - static int TOSTRING(lua_State *const) noexcept; - - method_list metaMethods = { luaRegDefaultGC, - LUA_DECL_META_METHOD(FunctionDeclaration, "__tostring", TOSTRING) }; - method_list methods = { LUA_DECL_METHOD(FunctionDeclaration, setName), - LUA_DECL_METHOD(FunctionDeclaration, setImportFromScript), - LUA_DECL_METHOD(FunctionDeclaration, pushToRuntime), - LUA_DECL_CREATE(FunctionDeclaration) }; - - bool isImported{ false }; - int functionRegisterKey{ -1 }; - -public: - std::string name{}; - std::string parentScript{}; - - bool isLocalToModule() const noexcept; - void pushLuaFunction(lua_State *const) const noexcept; - void getLuaFunctionFromStack(lua_State *const) noexcept; -}; - -// Module declaration -script_class (ModuleDeclaration) { - LUA_SCRIPTABLE_CLASS(ModuleDeclaration) - - static int setName(lua_State *const) noexcept; - static int setAuthorName(lua_State *const) noexcept; - static int setRevision(lua_State *const) noexcept; - static int setDescription(lua_State *const) noexcept; - static int setImports(lua_State *const) noexcept; - static int setOptions(lua_State *const) noexcept; - static int setFunctions(lua_State *const) noexcept; - static int setJobs(lua_State *const) noexcept; - - static int pushToRuntime(lua_State *const) noexcept; - - static int importMethod(lua_State *const) noexcept; - static int exportMethod(lua_State *const) noexcept; - - method_list metaMethods = { luaRegDefaultGC }; - method_list methods = { - LUA_DECL_METHOD(ModuleDeclaration, setName), - LUA_DECL_METHOD(ModuleDeclaration, setDescription), - LUA_DECL_METHOD(ModuleDeclaration, setRevision), - LUA_DECL_METHOD(ModuleDeclaration, setAuthorName), - LUA_DECL_METHOD(ModuleDeclaration, setImports), - LUA_DECL_METHOD(ModuleDeclaration, setOptions), - LUA_DECL_METHOD(ModuleDeclaration, setFunctions), - LUA_DECL_METHOD(ModuleDeclaration, setJobs), - LUA_DECL_METHOD(ModuleDeclaration, pushToRuntime), - LUA_DECL_NAMED_METHOD(ModuleDeclaration, "import", importMethod), - LUA_DECL_NAMED_METHOD(ModuleDeclaration, "export", exportMethod), - LUA_DECL_CREATE(ModuleDeclaration), - }; - - // Will be resolved later - std::vector<std::string> importNames{}; - std::vector<const ModuleDeclaration *> importedModules{}; - - void validateModule(lua_State *const) const noexcept; - int exportFunction(lua_State *const, const int tableIndex, const std::string_view) noexcept; - int exportJob(lua_State *const, const int tableIndex, const std::string_view, - const std::string_view) noexcept; - -public: - std::string moduleName{}; - std::string authorName{}; - std::string revision{}; - std::string moduleDescription{}; - std::vector<OptionDeclaration *> moduleOptions{}; - std::vector<FunctionDeclaration *> moduleFunctions{}; - std::vector<JobDeclaration *> moduleJobs{}; - - bool resolvModules(LuaContext *const) noexcept; -}; - -// Holds all the free functions (well, not really free functions here...) -script_class (FreeFunctions) { - LUA_SCRIPTABLE_CLASS_MANUAL_CTOR(FreeFunctions) - - FreeFunctions(lua_State *const) noexcept; - - static int print(lua_State *const) noexcept; - static int getModule(lua_State *const) noexcept; - - LUA_DECL_GETTER(int, start, audioStart) - LUA_DECL_GETTER(int, finish, audioFinish) - LUA_DECL_GETTER(int, width, videoWidth) - LUA_DECL_GETTER(int, height, videoHeight) - - method_list metaMethods = { luaRegDefaultGC }; - method_list methods = { LUA_DECL_METHOD(FreeFunctions, getModule), - LUA_DECL_METHOD(FreeFunctions, start), - LUA_DECL_METHOD(FreeFunctions, finish), - LUA_DECL_METHOD(FreeFunctions, width), - LUA_DECL_METHOD(FreeFunctions, height), - LUA_DECL_METHOD(FreeFunctions, print), - LUA_DECL_CREATE(FreeFunctions) }; - - int videoWidth{ 0 }, videoHeight{ 0 }; - int audioStart{ 0 }, audioFinish{ 0 }; -}; -} diff --git a/src/Lib/Script/CRTPLuaScriptObject/FreeFunctions.cc b/src/Lib/Script/CRTPLuaScriptObject/FreeFunctions.cc deleted file mode 100644 index 26ab5865..00000000 --- a/src/Lib/Script/CRTPLuaScriptObject/FreeFunctions.cc +++ /dev/null @@ -1,57 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/CRTPLuaScriptObject.hh" -#include "Lib/Script/LuaContext.hh" -#include "Lib/Document/CRTPSubDocument.hh" -#include "Lib/Document/VivyDocument.hh" -#include "Lib/Audio.hh" -#include "Lib/Video.hh" -#include "VivyApplication.hh" - -using namespace Vivy::Script; - -FreeFunctions::FreeFunctions(lua_State *const L) noexcept -{ - const auto *const context = LuaContext::getContext(L); - out(context) << "Creating the FreeFunctions lua object!"; - - std::shared_ptr<VivyDocument> vivyDoc = context->getAttachedVivyDocument(); - if (vivyDoc) { - if (!(vivyDoc->checkDocumentCapabilities(VivyDocument::AudioAble) && - vivyDoc->checkDocumentCapabilities(VivyDocument::AssAble) && - vivyDoc->checkDocumentCapabilities(VivyDocument::AudioAble))) { - err(context) << "The VivyDocument is not a complete document, " - << "can't load it for scripting"; - luaGlobalError(L, "Attached VivyDocument is not complete"); - } - - out(context) << "Initializing the FreeFunctions lua object with the VivyDocument"; - std::shared_ptr<VideoStream> video = vivyDoc->getVideoSubDocument()->getDefaultStream(); - [[maybe_unused]] std::shared_ptr<AudioStream> audio = - vivyDoc->getAudioSubDocument()->getDefaultStream(); - - videoWidth = video->getWidth(); - videoHeight = video->getWidth(); - TODO(Set getters values for audio) - } - - else { - out(context) << "No attached Vivy document in the Lua context"; - } -} - -int -FreeFunctions::print(lua_State *const L) noexcept -{ - const std::string_view arg = CHECK_STRING_VIEW(L, 1); - out(LuaContext::getContext(L)) << "OUT: " << arg; - LUA_RETURN_NOTHING(L); -} - -int -FreeFunctions::getModule(lua_State *const L) noexcept -{ - const auto *const context = LuaContext::getContext(L); - const std::string_view modName = CHECK_STRING_VIEW(L, 1); - [[maybe_unused]] const ModuleDeclaration *const mod = context->getModule(modName); - return 1; -} diff --git a/src/Lib/Script/CRTPLuaScriptObject/FunctionDeclaration.cc b/src/Lib/Script/CRTPLuaScriptObject/FunctionDeclaration.cc deleted file mode 100644 index c55679ca..00000000 --- a/src/Lib/Script/CRTPLuaScriptObject/FunctionDeclaration.cc +++ /dev/null @@ -1,69 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/CRTPLuaScriptObject.hh" - -using namespace Vivy::Script; - -int -FunctionDeclaration::TOSTRING(lua_State *const L) noexcept -{ - FunctionDeclaration *const self = CHECK(L, 1); - std::string str(className); - str += std::string_view(" { "); - str += self->parentScript.empty() ? self->name : self->parentScript + "::" + self->name; - str += std::string_view(" }"); - lua_pushstring(L, str.c_str()); - return 1; -} - -int -FunctionDeclaration::setName(lua_State *const L) noexcept -{ - FunctionDeclaration::CHECK(L, 1)->name = CHECK_STRING_VIEW(L, 2); - LUA_RETURN_NOTHING(L); -} - -int -FunctionDeclaration::setImportFromScript(lua_State *const L) noexcept -{ - auto *const fun = FunctionDeclaration::CHECK(L, 1); - fun->parentScript = CHECK_STRING_VIEW(L, 2); - fun->isImported = true; - LUA_RETURN_NOTHING(L); -} - -int -FunctionDeclaration::pushToRuntime(lua_State *const L) noexcept -{ - FunctionDeclaration *const self = CHECK(L, 1); - auto *const context = LuaContext::getContext(L); - - lua_settop(L, 1); - - if (self->isImported) - err(context) << "The function \"" << self->parentScript << "::" << self->name - << "\" is an imported function"; - - else if (context->registerDeclaration(self) == LuaContext::Code::Error) - context->failedWith("Failed to register function " + self->name); - - LUA_RETURN_NOTHING(L); -} - -void -FunctionDeclaration::pushLuaFunction(lua_State *const L) const noexcept -{ - [[maybe_unused]] bool ok = PushFunctionFromRegistry(L, functionRegisterKey); -} - -bool -FunctionDeclaration::isLocalToModule() const noexcept -{ - return parentScript.size() == 0; -} - -void -FunctionDeclaration::getLuaFunctionFromStack(lua_State *const L) noexcept -{ - luaL_checktype(L, -1, LUA_TFUNCTION); - functionRegisterKey = luaL_ref(L, LUA_REGISTRYINDEX); -} diff --git a/src/Lib/Script/CRTPLuaScriptObject/JobDeclaration.cc b/src/Lib/Script/CRTPLuaScriptObject/JobDeclaration.cc deleted file mode 100644 index 008dfc43..00000000 --- a/src/Lib/Script/CRTPLuaScriptObject/JobDeclaration.cc +++ /dev/null @@ -1,101 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/CRTPLuaScriptObject.hh" - -using namespace Vivy::Script; - -int -JobDeclaration::TOSTRING(lua_State *const L) noexcept -{ - JobDeclaration *const self = CHECK(L, 1); - std::string str(className); - str += std::string_view(" { "); - - str += self->parentScript.empty() ? self->name : self->parentScript + "::" + self->name; - str += ", options: ["; - - for (const OptionDeclaration *const opt : self->options) { - for (auto const &[name, _] : opt->options) - str += " " + name; - } - - str += std::string_view(" ] }"); - lua_pushstring(L, str.c_str()); - return 1; -} - -int -JobDeclaration::setName(lua_State *L) noexcept -{ - JobDeclaration::CHECK(L, 1)->name = CHECK_STRING_VIEW(L, 2); - LUA_RETURN_NOTHING(L); -} - -int -JobDeclaration::setOptions(lua_State *L) noexcept -{ - auto *const context = LuaContext::getContext(L); - JobDeclaration *const job = JobDeclaration::CHECK(L, 1); - err(context) << "Set options for job '" << job->name << "'"; - - IterateOverArray(L, 2, [&context, job, L]() noexcept -> bool { - OptionDeclaration *opt = OptionDeclaration::CHECK(L, -1); - - for (const auto &[name, value] : opt->options) { - err(context) << "\tregister option \"" << name << "\" with type \"" - << value.getSignature() << "\""; - } - - job->options.push_back(opt); - job->addUserValue(L, 1); // Tie T[i] to job and pop stack - return true; // Value was popped from the stack - }); - - LUA_RETURN_NOTHING(L); -} - -int -JobDeclaration::setImportFromScript(lua_State *L) noexcept -{ - auto *const job = JobDeclaration::CHECK(L, 1); - job->parentScript = CHECK_STRING_VIEW(L, 2); - job->isImported = true; - LUA_RETURN_NOTHING(L); -} - -int -JobDeclaration::pushToRuntime(lua_State *const L) noexcept -{ - JobDeclaration *const self = CHECK(L, 1); - auto *const context = LuaContext::getContext(L); - - lua_settop(L, 1); - - if (self->isImported) - err(context) - << "The job \"" << self->parentScript << "::" << self->name << "\" is an imported job"; - - else if (context->registerDeclaration(self) == LuaContext::Code::Error) - context->failedWith("Failed to register job " + self->name); - - LUA_RETURN_NOTHING(L); -} - -bool -JobDeclaration::isLocalToModule() const noexcept -{ - return parentScript.size() == 0; -} - -void -JobDeclaration::pushLuaFunction(lua_State *const L) const noexcept -{ - [[maybe_unused]] bool ok = PushFunctionFromRegistry(L, functionRegisterKey); -} - -void -JobDeclaration::getLuaFunctionFromStack(lua_State *const L, const JobIteratorType itType) noexcept -{ - luaL_checktype(L, -1, LUA_TFUNCTION); - functionRegisterKey = luaL_ref(L, LUA_REGISTRYINDEX); - iterationType = itType; -} diff --git a/src/Lib/Script/CRTPLuaScriptObject/ModuleDeclaration.cc b/src/Lib/Script/CRTPLuaScriptObject/ModuleDeclaration.cc deleted file mode 100644 index dc18aef9..00000000 --- a/src/Lib/Script/CRTPLuaScriptObject/ModuleDeclaration.cc +++ /dev/null @@ -1,262 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/CRTPLuaScriptObject.hh" - -using namespace Vivy::Script; - -bool -ModuleDeclaration::resolvModules(LuaContext *const context) noexcept -{ - for (const auto &str : importNames) { - const ModuleDeclaration *const mod = context->getModule(str); - if (mod) - importedModules.emplace_back(mod); - - else - context->failedWith("Failed to find needed module: " + str); - } - return true; -} - -int -ModuleDeclaration::importMethod(lua_State *const L) noexcept -{ - auto *const context = LuaContext::getContext(L); - luaL_checktype(L, 2, LUA_TTABLE); - - // Get the module name - lua_pushinteger(L, 1); // Stack is { top: int, table, self } - lua_gettable(L, 2); // Stack is { top: str, table, self } - const std::string_view mod = CHECK_STRING_VIEW(L, 3); - - // Import a module - context->getModule(mod); // Stack is { top: nil | module, str, table, self } - - // Import a function if needed - if (lua_rawlen(L, 2) == 2) { - lua_pushinteger(L, 2); // Stack is { top: int, module, str, table, self } - lua_gettable(L, 2); // Stack is { top: str, module, str, table, self } - const std::string_view func = CHECK_STRING_VIEW(L, 5); - FunctionDeclaration *const function = context->getFunction(mod, func); - if (function) - function->pushLuaFunction(L); - // Stack is { top: nil | function, FunctionDeclaration, str, module, str, table, self } - } - - // Top of stack is nil | function | module - return 1; -} - -int -ModuleDeclaration::exportMethod(lua_State *const L) noexcept -{ - ModuleDeclaration *const self = CHECK(L, 1); - luaL_checktype(L, 2, LUA_TTABLE); - - // Stack will be { top: string, table, self } - lua_pushinteger(L, 1); - lua_gettable(L, 2); - const std::string_view objectName = CHECK_STRING_VIEW(L, -1); - - const lua_Unsigned len = lua_rawlen(L, 2); - if (len == 2) - return self->exportFunction(L, 2, objectName); - - else if (len == 3) { - lua_pushinteger(L, 2); - lua_gettable(L, 2); - const std::string_view jobItTypeStr = CHECK_STRING_VIEW(L, -1); - return self->exportJob(L, 2, objectName, jobItTypeStr); - } - - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::exportFunction(lua_State *const L, const int tableIndex, - const std::string_view name) noexcept -{ - auto *const context = LuaContext::getContext(L); - FunctionDeclaration *const func = context->getFunction(moduleName, name); - out(context) << "Export function " << moduleName << "::" << name; - - lua_pushinteger(L, 2); - lua_gettable(L, tableIndex); - func->getLuaFunctionFromStack(L); - - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::exportJob(lua_State *const L, const int tableIndex, const std::string_view name, - const std::string_view itTypeStr) noexcept -{ - auto *const context = LuaContext::getContext(L); - const JobIteratorType jobItType = getJobIteratorTypeFromString(itTypeStr); - JobDeclaration *const job = context->getJob(moduleName, name); - - if (jobItType != JobIteratorType::Line && jobItType != JobIteratorType::Syllabe) { - const std::string str(itTypeStr); - luaL_error(L, "The iteration type must be LINE or SYLLABE, got %s", str.c_str()); - } - - else { - out(context) << "Export job " << moduleName << "::" << name << "{" << itTypeStr << "}"; - - lua_pushinteger(L, 3); - lua_gettable(L, tableIndex); - job->getLuaFunctionFromStack(L, jobItType); - } - - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setName(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - self->moduleName = CHECK_STRING_VIEW(L, 2); - Utils::trim(self->moduleName); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setAuthorName(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - self->authorName = CHECK_STRING_VIEW(L, 2); - Utils::trim(self->authorName); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setRevision(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - self->revision = CHECK_STRING_VIEW(L, 2); - Utils::trim(self->revision); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setDescription(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - self->moduleDescription = CHECK_STRING_VIEW(L, 2); - Utils::trim(self->moduleDescription); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setImports(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - IterateOverArray(L, 2, [self, L]() noexcept -> bool { - std::string import(CHECK_STRING_VIEW(L, -1)); - Utils::trim(import); - self->importNames.emplace_back(import); - return false; // Value was not popped from stack! - }); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setOptions(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - IterateOverArray(L, 2, [self, L]() noexcept -> bool { - OptionDeclaration *const opt = OptionDeclaration::CHECK(L, -1); - self->moduleOptions.emplace_back(opt); - self->addUserValue(L, 1); // Tie the opt to the module - return true; // The value was popped from the stack - }); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setFunctions(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - IterateOverArray(L, 2, [self, L]() noexcept -> bool { - FunctionDeclaration *const fun = FunctionDeclaration::CHECK(L, -1); - if (fun->isLocalToModule()) - fun->parentScript = self->moduleName; - self->moduleFunctions.emplace_back(fun); - self->addUserValue(L, 1); // Tie the function to the module - return true; // The value was popped from the stack - }); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::setJobs(lua_State *const L) noexcept -{ - auto *const self = ModuleDeclaration::CHECK(L, 1); - IterateOverArray(L, 2, [self, L]() noexcept -> bool { - JobDeclaration *const job = JobDeclaration::CHECK(L, -1); - if (job->isLocalToModule()) - job->parentScript = self->moduleName; - self->moduleJobs.emplace_back(job); - self->addUserValue(L, 1); // Tie the job to the module - return true; // The value was popped from the stack - }); - LUA_RETURN_NOTHING(L); -} - -int -ModuleDeclaration::pushToRuntime(lua_State *const L) noexcept -{ - ModuleDeclaration *const self = CHECK(L, 1); - auto *const context = LuaContext::getContext(L); - - self->importNames.emplace_back(self->moduleName); // You can use localy defined things - Utils::uniqAndSort<std::string>(self->importNames); // Better for all std algorithms - - self->validateModule(L); // May abort the LUA context - err(context) << "Register module " << VIVY_LOG_QUOTED(self->moduleName) << " in the runtime!"; - lua_settop(L, 1); - - if (context->registerDeclaration(self) == LuaContext::Code::Error) - context->failedWith("Failed to register module " + self->moduleName); - - TODO(Import needed modules here !) - - LUA_RETURN_NOTHING(L); -} - -void -ModuleDeclaration::validateModule(lua_State *const L) const noexcept -{ - // Minimal module file - if (moduleName.empty() || authorName.empty()) - luaGlobalError(L, "The module does not have the minimal required information"); - - // Imports - { - std::vector<std::string> usedImports{}; - const auto getUsedImports = [&usedImports](auto vectorOfPtr) noexcept -> void { - for (const auto *ptr : vectorOfPtr) { - if (!ptr->parentScript.empty()) - usedImports.emplace_back(ptr->parentScript); - } - }; - - getUsedImports(moduleJobs); - getUsedImports(moduleFunctions); - - Utils::uniqAndSort<std::string>(usedImports); - std::vector<std::string> unusedImports = - Utils::sortedSetDifference(usedImports, importNames); - - if (!unusedImports.empty()) { - std::size_t stringSize = 0; - std::string listStrImports = - "There are imported modules that are used withour begin declared:"; - for (const auto &str : unusedImports) - stringSize += 1 + str.size(); - listStrImports.reserve(stringSize); - for (const auto &str : unusedImports) - listStrImports += " " + str; - luaGlobalError(L, listStrImports); - } - } -} diff --git a/src/Lib/Script/CRTPLuaScriptObject/OptionDeclaration.cc b/src/Lib/Script/CRTPLuaScriptObject/OptionDeclaration.cc deleted file mode 100644 index c0881e13..00000000 --- a/src/Lib/Script/CRTPLuaScriptObject/OptionDeclaration.cc +++ /dev/null @@ -1,48 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/CRTPLuaScriptObject.hh" - -using namespace Vivy::Script; - -int -OptionDeclaration::TOSTRING(lua_State *const L) noexcept -{ - OptionDeclaration *const self = CHECK(L, 1); - std::string str(className); - str += std::string_view(" { "); - - for (auto const &[name, opt] : self->options) { - str += "\"" + name + "\" -> "; - str += opt.getSignature(); - str += ", "; - } - - str.resize(str.size() - 2); // Delete the leading ", " - str += std::string_view(" }"); - lua_pushstring(L, str.c_str()); - return 1; -} - -int -OptionDeclaration::addOptionContent(lua_State *const L) noexcept -{ - OptionDeclaration *const self = CHECK(L, 1); - luaL_checktype(L, 2, LUA_TSTRING); - - const std::string_view optName = CHECK_STRING_VIEW(L, 2); - const int valueType = lua_type(L, 3); - - // XXX: Add support for other types! - if (valueType == LUA_TNUMBER) - self->options.emplace(optName, lua_tonumber(L, 3)); - - else if (valueType == LUA_TSTRING) - self->options.emplace(optName, CHECK_STRING_VIEW(L, 3)); - - else if (valueType == LUA_TBOOLEAN) - self->options.emplace(optName, static_cast<bool>(lua_toboolean(L, 3))); - - else - luaL_error(L, "Unsupported type %s", luaL_typename(L, 3)); - - LUA_RETURN_NOTHING(L); -} diff --git a/src/Lib/Script/LuaContext.cc b/src/Lib/Script/LuaContext.cc deleted file mode 100644 index de8ab602..00000000 --- a/src/Lib/Script/LuaContext.cc +++ /dev/null @@ -1,297 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/CRTPLuaScriptObject.hh" -#include "Lib/Script/ScriptDocument.hh" -#include "Lib/Script/LuaContext.hh" -#include "Lib/Document/VivyDocument.hh" - -// LuaContext implementation -using namespace Vivy::Script; - -LuaContext::LuaContext() noexcept - : L(luaL_newstate()) -{ - luaL_openlibs(L); - - // Register this context - contextList.emplace(L, this); - - // Load all C++ objects - FreeFunctions::Register(L); - OptionDeclaration::Register(L); - JobDeclaration::Register(L); - FunctionDeclaration::Register(L); - ModuleDeclaration::Register(L); - - // Load the lib - loadPackagedFile(":lua/lib.lua"); - loadPackagedFile(":lua/module.lua"); -} - -LuaContext::~LuaContext() noexcept -{ - lua_close(L); // Close lua - contextList.erase(L); // Unregister the context -} - -void -LuaContext::loadPackagedFile(const QString &url) noexcept -{ - currentFile = url.toStdString(); - QFile libVivy(url); - if (!libVivy.open(QIODevice::ReadOnly | QIODevice::Text)) - qFatal("FATA -> failed to find packaged Vivy file %s", url.toStdString().c_str()); - loadString(libVivy.readAll().toStdString().c_str()); - currentFile = ""; -} - -LuaContext * -LuaContext::getContext(const lua_State *const state) noexcept -{ - return contextList.contains(state) ? contextList.at(state) : nullptr; -} - -LuaContext::Code -LuaContext::loadDocument(std::shared_ptr<Vivy::VivyDocument> doc) noexcept -{ - if (attachedVivyDocument != nullptr) - return Error; - attachedVivyDocument = doc; - return Success; -} - -LuaContext::Code -LuaContext::loadDocument(std::shared_ptr<ScriptDocument> doc) noexcept -{ - const QFileInfo fileCheck(doc->getName()); - if (!fileCheck.exists()) { - err(this) << "File " << doc->getName().toStdString() << " for document " - << doc->getUuid().toString().toStdString() << " doesn't exists"; - return Code::Error; - } - - lastLoadedModule = ""; - const auto rc = loadFile(fileCheck.absoluteFilePath().toStdString().c_str()); - if (rc != Code::Success) { - setFailedWith("Failed to load the module file"); - return rc; - } - - if (lastLoadedModule.empty()) { - setFailedWith("No module was loaded"); - return Code::Error; - } - - return Code::Success; -} - -void -LuaContext::swapEnv() noexcept -{ - lua_setglobal(L, "vivy"); -} - -LuaContext::Code -LuaContext::exec() noexcept -{ - if (lua_pcall(L, 0, 0, 0) != LUA_OK) { - err(this) << getLastLuaError().toStdString().c_str(); - return Code::Error; - } - return Code::Success; -} - -LuaContext::Code -LuaContext::loadString(const char *str) noexcept -{ - if (luaL_loadstring(L, str) != LUA_OK) { - err(this) << "Error loading string: " << getLastLuaError(); - return Code::Error; - } - return exec(); -} - -LuaContext::Code -LuaContext::loadFile(const char *file) noexcept -{ - currentFile = file; - if (luaL_loadfile(L, file) != LUA_OK) { - err(this) << "Error loading file " << file << ": " << getLastLuaError(); - currentFile = ""; - return Code::Error; - } - auto rc = exec(); - currentFile = ""; - return rc; -} - -QString -LuaContext::getLastLuaError() noexcept -{ - const int type = lua_type(L, -1); - if (type != LUA_TSTRING) { - return QStringLiteral("No lua error detected..."); - } - - QString ret = QString::fromUtf8(lua_tostring(L, -1)); - lua_pop(L, 1); - return ret; -} - -void -LuaContext::failedWith(const std::string &errorMessage) noexcept -{ - failedWith(errorMessage.c_str()); -} - -void -LuaContext::failedWith(const char *errorMessage) noexcept -{ - setFailedWith(errorMessage); - lua_error(L); - exit(EXIT_FAILURE); // Should not be there! -} - -void -LuaContext::setFailedWith(const char *errorMessage) noexcept -{ - lua_pushstring(L, errorMessage); -} - -void -LuaContext::setFailedWith(const std::string &errorMessage) noexcept -{ - setFailedWith(errorMessage.c_str()); -} - -lua_State * -LuaContext::getState() noexcept -{ - return L; -} - -std::shared_ptr<Vivy::VivyDocument> -LuaContext::getAttachedVivyDocument() const noexcept -{ - return attachedVivyDocument; -} - -bool -LuaContext::moduleExists(const std::string_view mod) const noexcept -{ - return modules.count(mod) >= 1; -} - -LuaContext::Code -LuaContext::registerDeclaration(const FunctionDeclaration *const fun) noexcept -{ - FunctionDeclaration::CHECK(L, -1); - return registerToMapTuple(fun->parentScript, fun->name, &functions); -} - -LuaContext::Code -LuaContext::registerDeclaration(const JobDeclaration *const job) noexcept -{ - JobDeclaration::CHECK(L, -1); - return registerToMapTuple(job->parentScript, job->name, &jobs); -} - -LuaContext::Code -LuaContext::registerToMapTuple(const std::string_view module, const std::string_view name, - std::map<std::tuple<const std::string_view, const std::string_view>, - const int> *const map) noexcept -{ - if (map->count({ module, name }) >= 1) - return Error; - - logInfo() << "Register " << module << "::" << name; - - // WARN: The object needs to be already checked! - const int r = luaL_ref(L, LUA_REGISTRYINDEX); - map->emplace(std::tuple{ module, name }, r); - return Success; -} - -LuaContext::Code -LuaContext::registerDeclaration(const ModuleDeclaration *const mod) noexcept -{ - if (moduleExists(mod->moduleName)) { - logError() - << "The module " << VIVY_LOG_QUOTED(mod->moduleName) << " is already registered!"; - return Code::Error; - } - - logInfo() << "Register module " << VIVY_LOG_QUOTED(mod->moduleName); - - ModuleDeclaration::CHECK(L, -1); - const int r = luaL_ref(L, LUA_REGISTRYINDEX); - modules.emplace(mod->moduleName, r); - lastLoadedModule = mod->moduleName; - return Code::Success; -} - -ModuleDeclaration * -LuaContext::getModule(const std::string_view name) const noexcept -{ - if (moduleExists(name)) { - const int r = modules.at(name); - lua_rawgeti(L, LUA_REGISTRYINDEX, r); - return ModuleDeclaration::CHECK(L, -1); - } - - else { - const std::string moduleName(name); - luaL_error(L, "Module %s not found", moduleName.c_str()); - return nullptr; - } -} - -FunctionDeclaration * -LuaContext::getFunction(const std::string_view module, const std::string_view name) const noexcept -{ - if (moduleExists(module)) { - const int r = functions.at({ module, name }); - lua_rawgeti(L, LUA_REGISTRYINDEX, r); - return FunctionDeclaration::CHECK(L, -1); - } - - else { - const std::string moduleName(module); - const std::string functionName(name); - luaL_error(L, "Function %s::%s not found", moduleName.c_str(), functionName.c_str()); - return nullptr; - } -} - -JobDeclaration * -LuaContext::getJob(const std::string_view module, const std::string_view name) const noexcept -{ - if (moduleExists(module) && jobs.count({ module, name }) >= 1) { - const int r = jobs.at({ module, name }); - lua_rawgeti(L, LUA_REGISTRYINDEX, r); - return JobDeclaration::CHECK(L, -1); - } - - else { - const std::string moduleName(module); - const std::string jobName(name); - luaL_error(L, "Job %s::%s not found", moduleName.c_str(), jobName.c_str()); - return nullptr; // Unreachable - } -} - -const std::vector<std::string_view> -LuaContext::getAllModuleName() const noexcept -{ - std::vector<std::string_view> moduleNames{}; - for (auto const &[name, _] : modules) - moduleNames.emplace_back(name); - return moduleNames; -} - -const std::string & -LuaContext::getCurrentLuaFile() const -{ - if (currentFile.empty()) - throw std::logic_error("Not called when a file is being evaluated"); - return currentFile; -} diff --git a/src/Lib/Script/LuaContext.hh b/src/Lib/Script/LuaContext.hh deleted file mode 100644 index ba1b30d0..00000000 --- a/src/Lib/Script/LuaContext.hh +++ /dev/null @@ -1,119 +0,0 @@ -#pragma once - -#include "PreCompiledHeaders.hh" -#include "VivyApplication.hh" -#include "Lib/Log.hh" -#include "Lib/Utils.hh" - -struct lua_State; - -namespace Vivy -{ -class ScriptDocument; -class VivyDocument; -} - -namespace Vivy::Script -{ -class ScriptStore; -class ModuleDeclaration; -class FunctionDeclaration; -class JobDeclaration; -} - -namespace Vivy::Script -{ -// New Lua script instance -class LuaContext final { - VIVY_UNMOVABLE_OBJECT(LuaContext) - VIVY_APP_LOGGABLE_OBJECT(LuaContext, logger) - - lua_State *L{ nullptr }; - std::shared_ptr<Vivy::VivyDocument> attachedVivyDocument{ nullptr }; - - std::string failureString{}; - std::string currentFile{}; - std::string lastLoadedModule{}; - - std::map<const std::string_view, const int> modules = {}; - std::map<std::tuple<const std::string_view, const std::string_view>, const int> functions = {}; - std::map<std::tuple<const std::string_view, const std::string_view>, const int> jobs = {}; - - static inline std::map<const lua_State *const, LuaContext *const> contextList = {}; - -public: - enum class Code { Success, Error }; - static constexpr inline Code Success = Code::Success; - static constexpr inline Code Error = Code::Error; - - LuaContext() noexcept; - ~LuaContext() noexcept; - - Code loadDocument(std::shared_ptr<ScriptDocument>) noexcept; - Code loadDocument(std::shared_ptr<Vivy::VivyDocument>) noexcept; - - QString getLastLuaError() noexcept; - - // Fail and abort the LuaContext - [[noreturn]] void failedWith(const std::string &) noexcept; - [[noreturn]] void failedWith(const char *) noexcept; - - // Set the error message for the lua context and continue - void setFailedWith(const char *) noexcept; - void setFailedWith(const std::string &) noexcept; - - lua_State *getState() noexcept; - std::shared_ptr<Vivy::VivyDocument> getAttachedVivyDocument() const noexcept; - - decltype(auto) getOutputStream() const noexcept { return logInfo(); } - decltype(auto) getErrorStream() const noexcept { return logError(); } - - operator lua_State *() noexcept { return L; } - static LuaContext *getContext(const lua_State *const) noexcept; - - // WARN: Need the ModuleDeclaration, the FunctionDeclaration and the - // JobDeclaration to be on top of the stack! - Code registerDeclaration(const ModuleDeclaration *const) noexcept; - Code registerDeclaration(const FunctionDeclaration *const) noexcept; - Code registerDeclaration(const JobDeclaration *const) noexcept; - - // Returns the module or `nullptr` if not found. - ModuleDeclaration *getModule(const std::string_view) const noexcept; - FunctionDeclaration *getFunction(const std::string_view, const std::string_view) const noexcept; - JobDeclaration *getJob(const std::string_view, const std::string_view) const noexcept; - const std::vector<std::string_view> getAllModuleName() const noexcept; - - // Makes only sens when called from within loadFile and loadPackagedFile - const std::string &getCurrentLuaFile() const; - void setLastLoadedModule(const std::string &) noexcept; - -private: - // Exec all loaded strings and files - Code exec() noexcept; - - Code loadString(const char *) noexcept; - Code loadFile(const char *) noexcept; - void loadPackagedFile(const QString &) noexcept; - - Code registerToMapTuple(const std::string_view module, const std::string_view name, - std::map<std::tuple<const std::string_view, const std::string_view>, - const int> *const mapPtr) noexcept; - bool moduleExists(const std::string_view) const noexcept; - - // Swap the env, needed before executing a user script! - void swapEnv() noexcept; -}; - -[[maybe_unused]] static inline decltype(auto) -out(const LuaContext *const context) noexcept -{ - return context->getOutputStream(); -} - -[[maybe_unused]] static inline decltype(auto) -err(const LuaContext *const context) noexcept -{ - return context->getErrorStream(); -} - -} diff --git a/src/Lib/Script/ScriptDocument.cc b/src/Lib/Script/ScriptDocument.cc deleted file mode 100644 index 4aa46d0e..00000000 --- a/src/Lib/Script/ScriptDocument.cc +++ /dev/null @@ -1,56 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/ScriptDocument.hh" - -#include <QFileInfo> -#include <QFile> -#include <QTextStream> - -using namespace Vivy; - -ScriptDocument::ScriptDocument(const QString &path) - : AbstractDocument(AbstractDocument::Type::Script, path) -{ - const QFileInfo file(path); - if (!file.exists()) - throw std::runtime_error("File don't exists, don't create ScriptDocument"); -} - -void -ScriptDocument::copy(const QString &newName) -{ - /* Compute new paths */ - const QFileInfo newPath(newName); - copyWith(newPath, [=, this]() noexcept { name = newName; }); - emit documentChanged(); -} - -void -ScriptDocument::rename(const QString &newName) -{ - /* Compute new paths */ - const QFileInfo newPath(newName); - renameWith(newPath, [=, this]() noexcept { name = newName; }); - emit documentChanged(); -} - -void -ScriptDocument::save() -{ - if (!textDocument) - throw std::runtime_error("no text document attached to the ScriptDocument!"); - - QFile file(name); - if (file.open(QIODevice::WriteOnly, QIODevice::Text)) { - throw std::runtime_error("Failed to open file in WO+Text mode: " + name.toStdString()); - } - - QTextStream writter(&file); - writter << textDocument->toPlainText(); - file.close(); -} - -void -ScriptDocument::attachTextDocument(const QTextDocument *const txt) noexcept -{ - textDocument = txt; -} diff --git a/src/Lib/Script/ScriptDocument.hh b/src/Lib/Script/ScriptDocument.hh deleted file mode 100644 index 7d13e129..00000000 --- a/src/Lib/Script/ScriptDocument.hh +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#ifndef __cplusplus -#error "This is a C++ header" -#endif - -#include "PreCompiledHeaders.hh" -#include "Lib/AbstractDocument.hh" -#include "Lib/Uuid.hh" - -class QTextDocument; - -namespace Vivy -{ -class ScriptDocument final : public AbstractDocument { -public: - explicit ScriptDocument(const QString &name); - - void copy(const QString &) override; - void rename(const QString &) override; - void save() override; - - void attachTextDocument(const QTextDocument *const) noexcept; - -private: - const QTextDocument *textDocument{ nullptr }; -}; -} diff --git a/src/Lib/Script/ScriptOption.cc b/src/Lib/Script/ScriptOption.cc deleted file mode 100644 index 3c855cf7..00000000 --- a/src/Lib/Script/ScriptOption.cc +++ /dev/null @@ -1,63 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/ScriptOption.hh" - -// OptionDeclaration -using namespace Vivy::Script; - -ScriptOption::ScriptOption(const std::string &str) noexcept - : string(str) - , type(Type::String) -{ -} - -ScriptOption::ScriptOption(const std::string_view str) noexcept - : string(str) - , type(Type::String) -{ -} - -ScriptOption::ScriptOption(double n) noexcept - : number(n) - , type(Type::Number) -{ -} - -ScriptOption::ScriptOption(bool b) noexcept - : boolean(b) - , type(Type::Boolean) -{ -} - -std::string * -ScriptOption::getString() noexcept -{ - return type == Type::String ? &string : nullptr; -} - -double * -ScriptOption::getNumber() noexcept -{ - return type == Type::Number ? &number : nullptr; -} - -bool * -ScriptOption::getBoolean() noexcept -{ - return type == Type::Boolean ? &boolean : nullptr; -} - -std::string_view -ScriptOption::getSignature() const noexcept -{ - static constexpr std::string_view signatureNumber = "Number"; - static constexpr std::string_view signatureString = "String"; - static constexpr std::string_view signatureBoolean = "Boolean"; - switch (type) { - case Type::String: return signatureString; - case Type::Number: return signatureNumber; - case Type::Boolean: return signatureBoolean; - } - - // Let the program crash - qFatal("UNREACHABLE"); -} diff --git a/src/Lib/Script/ScriptOption.hh b/src/Lib/Script/ScriptOption.hh deleted file mode 100644 index fc3c0607..00000000 --- a/src/Lib/Script/ScriptOption.hh +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include "PreCompiledHeaders.hh" - -namespace Vivy::Script -{ -// The options -class ScriptOption { - enum class Type { String, Number, Boolean }; - -private: - std::string string; - double number; - bool boolean; - - Type type; - -public: - ScriptOption(const std::string &) noexcept; - ScriptOption(const std::string_view) noexcept; - ScriptOption(bool) noexcept; - ScriptOption(double) noexcept; - - std::string *getString() noexcept; - double *getNumber() noexcept; - bool *getBoolean() noexcept; - - std::string_view getSignature() const noexcept; -}; -} diff --git a/src/Lib/Script/ScriptStore.cc b/src/Lib/Script/ScriptStore.cc deleted file mode 100644 index a046ffbd..00000000 --- a/src/Lib/Script/ScriptStore.cc +++ /dev/null @@ -1,83 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "Lib/Script/ScriptStore.hh" -#include "Lib/Uuid.hh" - -using namespace Vivy; -using namespace std::string_literals; -using Code = Script::LuaContext::Code; - -ScriptStore::ScriptStore() noexcept { resetLoadedScripts(); } - -void -ScriptStore::loadScriptFolder(const QString &folderPath) -{ - QDir folder(folderPath); - const auto filter = QDir::Files | QDir::NoSymLinks | QDir::Readable; - - // Load all module files, the loadDocument will ask for the implementation - // file. - for (const QString &file : folder.entryList(filter)) { - if (!Utils::scriptFileSuffix.contains(QFileInfo(file).suffix())) - continue; - - auto doc = loadDocument(file); - if (luaContext->loadDocument(doc) != Code::Success) { - const QString error = QStringLiteral("File: ") + file + QStringLiteral(" [") + - doc->getUuid().toString() + QStringLiteral("]") + - luaContext->getLastLuaError(); - throw std::runtime_error(error.toStdString()); - } - } -} - -std::vector<ScriptStore::Item> -ScriptStore::getLoadedScripts() const noexcept -{ - std::vector<ScriptStore::Item> ret; - for (auto const &[uuid, docPtr] : documents) - ret.emplace_back(Item{ uuid, docPtr->getName() }); - return ret; -} - -void -ScriptStore::resetLoadedScripts() noexcept -{ - luaContext.reset(new Script::LuaContext()); -} - -bool -ScriptStore::executeScript(Uuid id) noexcept -{ - const auto &script = documents.at(id); - return luaContext->loadDocument(script) == Code::Success; -} - -bool -ScriptStore::executeScript(Uuid id, std::shared_ptr<Vivy::VivyDocument> doc) noexcept -{ - if (doc == nullptr) - return false; - if (luaContext->loadDocument(doc) != Script::LuaContext::Success) { - luaContext->setFailedWith("A VivyDocument is already loaded, can't attach a new one"); - return false; - } - return executeScript(id); -} - -const std::vector<std::string_view> -ScriptStore::getLoadedModules() const noexcept -{ - return luaContext ? luaContext->getAllModuleName() : std::vector<std::string_view>{}; -} - -const Script::ModuleDeclaration * -ScriptStore::getModule(const std::string_view str) const noexcept -{ - return luaContext->getModule(str); -} - -QString -ScriptStore::getLastLuaError() noexcept -{ - return luaContext ? luaContext->getLastLuaError() : QString(); -} diff --git a/src/Lib/Script/ScriptStore.hh b/src/Lib/Script/ScriptStore.hh deleted file mode 100644 index f0af2d61..00000000 --- a/src/Lib/Script/ScriptStore.hh +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include "Lib/CRTPStore.hh" -#include "Lib/Document/VivyDocument.hh" -#include "Lib/Script/ScriptDocument.hh" -#include "Lib/Script/LuaContext.hh" - -namespace Vivy::Script -{ -class LuaContext; -class ModuleDeclaration; -} - -namespace Vivy -{ -class ScriptStore final : public CRTPStore<ScriptStore, ScriptDocument> { - VIVY_STORAGE_CLASS(ScriptStore, ScriptDocument) - - static constexpr inline int outBufferSize = 1024; - -public: - using Item = std::tuple<Uuid, QString>; - - explicit ScriptStore() noexcept; - - // Load scripts - void resetLoadedScripts() noexcept; - void loadScriptFolder(const QString &folderPath); - std::vector<Item> getLoadedScripts() const noexcept; - bool executeScript(Uuid) noexcept; - bool executeScript(Uuid, std::shared_ptr<Vivy::VivyDocument>) noexcept; - - QString getLastLuaError() noexcept; - - // Get modules from scripts - const std::vector<std::string_view> getLoadedModules() const noexcept; - const Script::ModuleDeclaration *getModule(const std::string_view) const noexcept; - -private: - std::unique_ptr<Script::LuaContext> luaContext{ nullptr }; -}; -} diff --git a/src/UI/DocumentViews/MpvWidget.cc b/src/UI/DocumentViews/MpvWidget.cc index 04e88150..9be916b6 100644 --- a/src/UI/DocumentViews/MpvWidget.cc +++ b/src/UI/DocumentViews/MpvWidget.cc @@ -239,14 +239,9 @@ MpvWidget::setPosition([[maybe_unused]] int sec) bool MpvWidget::loadFile(const QString &filepath) { - const bool ret = false; - throw std::runtime_error("lmpv_load_file"); - // const bool ret = !lmpv_load_file(mpv, filepath); - - if (ret) { - m_state = NONSTOPPED; - } - return ret; + const char *cmd[] = { "loadfile", filepath.toStdString().c_str(), nullptr }; + mpv_command_async(mpv, 0, cmd); + return true; } bool diff --git a/src/UI/MainWindow.cc b/src/UI/MainWindow.cc index d83a4b49..b6d80cb9 100644 --- a/src/UI/MainWindow.cc +++ b/src/UI/MainWindow.cc @@ -1,6 +1,5 @@ #include "PreCompiledHeaders.hh" #include "Lib/Document/VivyDocumentStore.hh" -#include "Lib/Script/ScriptStore.hh" #include "Lib/Utils.hh" #include "VivyApplication.hh" #include "UI/MainWindow.hh" @@ -184,8 +183,8 @@ MainWindow::updateFakeVimUsage(bool yes) noexcept const bool isScriptEditor = documentExists && (docView->getDocument()->getType() == AbstractDocument::Type::Script); - if (isScriptEditor) - static_cast<ScriptDocumentView *>(docView)->setUseFakeVimEditor(yes); + //if (isScriptEditor) + // static_cast<ScriptDocumentView *>(docView)->setUseFakeVimEditor(yes); }); } @@ -348,18 +347,18 @@ MainWindow::openDocument() noexcept if (fileType == Utils::DocumentType::Vivy) addTab(new VivyDocumentView(vivyApp->documentStore->loadDocument(filename), documents)); - else if (fileType == Utils::DocumentType::VivyScript) { - auto scriptDocument = vivyApp->scriptStore->loadDocument(filename); - const bool rc = vivyApp->scriptStore->executeScript(scriptDocument->getUuid()); - ScriptDocumentView *newView = new ScriptDocumentView(scriptDocument, documents); + //else if (fileType == Utils::DocumentType::VivyScript) { + // auto scriptDocument = vivyApp->scriptStore->loadDocument(filename); + // const bool rc = vivyApp->scriptStore->executeScript(scriptDocument->getUuid()); + // ScriptDocumentView *newView = new ScriptDocumentView(scriptDocument, documents); - if (!rc) { - const auto &[line, desc] = std::tuple{ 0, vivyApp->scriptStore->getLastLuaError() }; - emit newView->luaErrorFound(line, desc); - } + // if (!rc) { + // const auto &[line, desc] = std::tuple{ 0, vivyApp->scriptStore->getLastLuaError() }; + // emit newView->luaErrorFound(line, desc); + // } - addTab(newView); - } + // addTab(newView); + //} } catch (const std::runtime_error &e) { logError() << "Failed to load document " << VIVY_LOG_QUOTED(filename) << " with error: " << e.what(); diff --git a/src/UI/MainWindow.hh b/src/UI/MainWindow.hh index c462d7f9..2a3f437e 100644 --- a/src/UI/MainWindow.hh +++ b/src/UI/MainWindow.hh @@ -12,7 +12,6 @@ #include "Lib/Document/VivyDocumentStore.hh" #include "UI/DocumentViews/AudioVisualizer.hh" #include "UI/VivyDocumentView.hh" -#include "UI/ScriptDocumentView.hh" namespace Vivy { diff --git a/src/UI/ScriptDocumentView.cc b/src/UI/ScriptDocumentView.cc deleted file mode 100644 index 9fabc4b3..00000000 --- a/src/UI/ScriptDocumentView.cc +++ /dev/null @@ -1,142 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "UI/ScriptDocumentView.hh" -#include "UI/MainWindow.hh" -#include "UI/ScriptViews/ScriptEditor.hh" -#include "UI/ScriptViews/ScriptHighlighter.hh" -#include "VivyApplication.hh" - -using namespace Vivy; - -ScriptDocumentView::ScriptDocumentView(std::shared_ptr<ScriptDocument> ptr, QWidget *parent) - : AbstractDocumentView(AbstractDocumentView::Type::Script, parent) - , editor(new ScriptEditor(this)) - , syntax(new ScriptHighlighter(editor->document())) - , document(ptr) -{ - QFile textFile(ptr->getName()); - if (!textFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - throw std::runtime_error("Failed to open script file"); - } - - editor->setPlainText(QString::fromUtf8(textFile.readAll())); - setCentralWidget(editor); - editor->setFocus(Qt::OtherFocusReason); - - setUseFakeVimEditor(vivyApp->getUseFakeVimEditor()); - - connect(this, &ScriptDocumentView::luaErrorFound, editor, &ScriptEditor::updateLastLuaError); - connect(document.get(), &AbstractDocument::documentChanged, this, - [=, this]() noexcept -> void { emit documentPropertyChanged(); }); - - // Same style as the editor - setStyleSheet(QStringLiteral("* {" - " background-color: #232629;" - " font-family: \"FiraCode\";" - " font-size: 10pt" - "}")); - - VIVY_LOG_CTOR() << "Creating view for script " << VIVY_LOG_QUOTED(ptr->getName()) << " with " - << ptr->getUuid(); -} - -ScriptDocumentView::~ScriptDocumentView() -{ - setUseFakeVimEditor(false); - VIVY_LOG_DTOR() << "Closing a script view"; -} - -void -ScriptDocumentView::setUseFakeVimEditor(bool yes) noexcept -{ - if (yes && !isUsingFakeVim) { - MainWindow *const mw = vivyApp->getMainWindow(); - handler = new FakeVimHandler(editor); - proxy = EditorProxy::connectSignals(handler, editor); - isUsingFakeVim = true; - connect(proxy, &EditorProxy::handleInput, handler, &FakeVimHandler::handleInput); - connect(proxy, &EditorProxy::requestQuit, this, [this, mw]() noexcept -> void { - mw->closeDocument(static_cast<AbstractDocumentView *>(this)); - }); - connect(proxy, &EditorProxy::requestSave, this, [this]() { document->save(); }); - connect(proxy, &EditorProxy::requestSaveAndQuit, this, [this, mw]() noexcept -> void { - document->save(); - mw->closeDocument(static_cast<AbstractDocumentView *>(this)); - }); - initHandler(handler); - clearUndoRedo(editor); - } - - else if (!yes) { - if (handler) { - handler->disconnectFromEditor(); - delete handler; - } - - if (proxy) - delete proxy; - - clearUndoRedo(editor); - editor->setOverwriteMode(false); - isUsingFakeVim = false; - proxy = nullptr; - handler = nullptr; - } -} - -void -ScriptDocumentView::initHandler(FakeVimHandler *handler) noexcept -{ - handler->handleCommand(QStringLiteral("set nopasskeys")); - handler->handleCommand(QStringLiteral("set nopasscontrolkey")); - handler->installEventFilter(); - handler->setupWidget(); - - handler->handleCommand(QStringLiteral("set expandtab")); - handler->handleCommand(QStringLiteral("set shiftwidth=4")); - handler->handleCommand(QStringLiteral("set tabstop=4")); - handler->handleCommand(QStringLiteral("set autoindent")); - handler->handleCommand(QStringLiteral("set smartindent")); -} - -void -ScriptDocumentView::clearUndoRedo(QPlainTextEdit *scriptEditor) noexcept -{ - scriptEditor->setUndoRedoEnabled(false); - scriptEditor->setUndoRedoEnabled(true); -} - -void -ScriptDocumentView::closeDocument() noexcept -{ -} - -QString -ScriptDocumentView::getDocumentTabName() const noexcept -{ - const QFileInfo fileInfo(document->getName()); - return fileInfo.completeBaseName(); -} - -QString -ScriptDocumentView::getDocumentTabToolTip() const noexcept -{ - return QStringLiteral("UUID: ") + document->getUuid().toString() + - QStringLiteral("\nType: Vivy Script"); -} - -QIcon -ScriptDocumentView::getDocumentTabIcon() const noexcept -{ - return QIcon(VIVY_ICON_SCRIPT); -} - -AbstractDocument * -ScriptDocumentView::getDocument() const noexcept -{ - return document.get(); -} - -void -ScriptDocumentView::openProperties() noexcept -{ -} diff --git a/src/UI/ScriptDocumentView.hh b/src/UI/ScriptDocumentView.hh deleted file mode 100644 index a348e317..00000000 --- a/src/UI/ScriptDocumentView.hh +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef VIVY_SCRIPT_DOCUMENT_VIEW_H -#define VIVY_SCRIPT_DOCUMENT_VIEW_H - -#ifndef __cplusplus -#error "This is a C++ header" -#endif - -#include "PreCompiledHeaders.hh" -#include "VivyApplication.hh" -#include "Lib/Utils.hh" -#include "Lib/Log.hh" -#include "Lib/Script/ScriptDocument.hh" -#include "UI/AbstractDocumentView.hh" -#include "UI/FakeVim/FakeVimHandler.hh" -#include "UI/ScriptViews/EditorProxy.hh" -#include "UI/ScriptViews/ScriptHighlighter.hh" -#include "UI/ScriptViews/ScriptEditor.hh" - -namespace Vivy -{ -class ScriptDocumentView final : public AbstractDocumentView { - Q_OBJECT - VIVY_UNMOVABLE_OBJECT(ScriptDocumentView) - VIVY_APP_LOGGABLE_OBJECT(ScriptDocumentView, logger) - -public: - explicit ScriptDocumentView(std::shared_ptr<ScriptDocument>, QWidget *parent = nullptr); - ~ScriptDocumentView() override; - - void closeDocument() noexcept override; - void openProperties() noexcept override; - - QString getDocumentTabName() const noexcept override; - QString getDocumentTabToolTip() const noexcept override; - QIcon getDocumentTabIcon() const noexcept override; - AbstractDocument *getDocument() const noexcept override; - - void setUseFakeVimEditor(bool yes) noexcept; - -signals: - void luaErrorFound(int, QString); - -private: - ScriptEditor *editor{ nullptr }; - EditorProxy *proxy{ nullptr }; - ScriptHighlighter *syntax{ nullptr }; - FakeVimHandler *handler{ nullptr }; - std::shared_ptr<ScriptDocument> document{ nullptr }; - QString lastLuaErrorMsg{}; - int lastLuaErrorLine{ -1 }; - bool isUsingFakeVim{ false }; - - static void initHandler(FakeVimHandler *handler) noexcept; - static void clearUndoRedo(QPlainTextEdit *editor) noexcept; -}; -} - -#endif // VIVY_PROPERTY_DOCUMENT_VIEW_H diff --git a/src/UI/ScriptViews/EditorProxy.cc b/src/UI/ScriptViews/EditorProxy.cc deleted file mode 100644 index de96e991..00000000 --- a/src/UI/ScriptViews/EditorProxy.cc +++ /dev/null @@ -1,330 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "UI/ScriptViews/EditorProxy.hh" -#include "UI/MainWindow.hh" -#include "UI/FakeVim/FakeVimHandler.hh" -#include "UI/FakeVim/FakeVimActions.hh" -#include "VivyApplication.hh" - -using namespace Vivy; - -Vivy::EditorProxy * -EditorProxy::connectSignals(FakeVimHandler *handler, QPlainTextEdit *editor) noexcept -{ - EditorProxy *proxy = new EditorProxy(editor); - - handler->commandBufferChanged.connect( - [proxy](const QString &contents, int cursorPos, int, int) noexcept -> void { - proxy->changeStatusMessage(contents, cursorPos); - }); - - handler->extraInformationChanged.connect( - [proxy](const QString &text) noexcept -> void { proxy->changeExtraInformation(text); }); - handler->statusDataChanged.connect( - [proxy](const QString &text) noexcept -> void { proxy->changeStatusData(text); }); - handler->highlightMatches.connect( - [proxy](const QString &needle) noexcept -> void { proxy->highlightMatches(needle); }); - handler->handleExCommandRequested.connect( - [proxy](bool *handled, const ExCommand &cmd) noexcept -> void { - proxy->handleExCommand(handled, cmd); - }); - handler->requestSetBlockSelection.connect([proxy](const QTextCursor &cursor) noexcept -> void { - proxy->requestSetBlockSelection(cursor); - }); - handler->requestDisableBlockSelection.connect( - [proxy]() noexcept -> void { proxy->requestDisableBlockSelection(); }); - handler->requestHasBlockSelection.connect( - [proxy](bool *on) noexcept -> void { proxy->requestHasBlockSelection(on); }); - - handler->indentRegion.connect( - [proxy](int beginBlock, int endBlock, QChar typedChar) noexcept -> void { - proxy->indentRegion(beginBlock, endBlock, typedChar); - }); - handler->checkForElectricCharacter.connect([proxy](bool *result, QChar c) noexcept -> void { - proxy->checkForElectricCharacter(result, c); - }); - - return proxy; -} - -EditorProxy::EditorProxy(QPlainTextEdit *widg) noexcept - : QObject() - , widget(widg) -{ - VIVY_LOG_CTOR() - << "Creating new proxy for a the text view " << VIVY_LOG_QUOTED(widg->windowFilePath()); -} - -EditorProxy::~EditorProxy() { VIVY_LOG_DTOR() << "Delete editor proxy!"; } - -void -EditorProxy::changeStatusData(const QString &info) noexcept -{ - statusData = info; - updateStatusBar(); -} - -void -EditorProxy::highlightMatches(const QString &pattern) noexcept -{ - QTextDocument *doc = widget->document(); - Q_ASSERT(doc); - - QTextEdit::ExtraSelection selection; - selection.format.setBackground(Qt::yellow); - selection.format.setForeground(Qt::black); - - // Highlight matches. - QRegExp re(pattern); - QTextCursor cur = doc->find(re); - searchSelection.clear(); - - int a = cur.position(); - while (!cur.isNull()) { - if (cur.hasSelection()) { - selection.cursor = cur; - searchSelection.append(selection); - } else { - cur.movePosition(QTextCursor::NextCharacter); - } - - cur = doc->find(re, cur); - int b = cur.position(); - - if (a == b) { - cur.movePosition(QTextCursor::NextCharacter); - cur = doc->find(re, cur); - b = cur.position(); - if (a == b) - break; - } - - a = b; - } - - updateExtraSelections(); -} - -void -EditorProxy::changeStatusMessage(const QString &contents, int cursorPos) noexcept -{ - statusMessage = (cursorPos == -1) - ? contents - : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos); - updateStatusBar(); -} - -void -EditorProxy::changeExtraInformation(const QString &info) noexcept -{ - QMessageBox::information(widget, tr("Information"), info); -} - -void -EditorProxy::updateStatusBar() noexcept -{ - vivyApp->getMainWindow()->statusBar()->showMessage(statusMessage); // + statusData -} - -void -EditorProxy::handleExCommand(bool *handled, const ExCommand &cmd) noexcept -{ - // :wq - if (wantSaveAndQuit(cmd)) - emit requestSaveAndQuit(); - - // :w - else if (wantSave(cmd)) - emit requestSave(); - - else if (wantQuit(cmd)) { - // :q! - if (cmd.hasBang) { - logInfo() << "Want to force quit the editor!"; - emit requestQuit(); - } - - // :q - else { - logInfo() << "Want to quit the editor"; - emit requestQuit(); - } - } - - else if (wantRun(cmd)) - emit requestRun(); - - else { - *handled = false; - return; - } - - *handled = true; -} - -void -EditorProxy::requestSetBlockSelection(const QTextCursor &tc) noexcept -{ - const QPalette pal = widget->parentWidget() != nullptr ? widget->parentWidget()->palette() - : QApplication::palette(); - - blockSelection.clear(); - clearSelection.clear(); - - QTextCursor cur = tc; - - QTextEdit::ExtraSelection selection; - selection.format.setBackground(pal.color(QPalette::Base)); - selection.format.setForeground(pal.color(QPalette::Text)); - selection.cursor = cur; - clearSelection.append(selection); - - selection.format.setBackground(pal.color(QPalette::Highlight)); - selection.format.setForeground(pal.color(QPalette::HighlightedText)); - - const int from = cur.positionInBlock(); - const int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position(); - const int min = qMin(cur.position(), cur.anchor()); - const int max = qMax(cur.position(), cur.anchor()); - for (QTextBlock block = cur.document()->findBlock(min); - block.isValid() && block.position() < max; block = block.next()) { - cur.setPosition(block.position() + qMin(from, block.length())); - cur.setPosition(block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor); - selection.cursor = cur; - blockSelection.append(selection); - } - - disconnect(widget, &QPlainTextEdit::selectionChanged, this, &EditorProxy::updateBlockSelection); - widget->setTextCursor(tc); - connect(widget, &QPlainTextEdit::selectionChanged, this, &EditorProxy::updateBlockSelection); - - QPalette pal2 = widget->palette(); - pal2.setColor(QPalette::Highlight, Qt::transparent); - pal2.setColor(QPalette::HighlightedText, Qt::transparent); - widget->setPalette(pal2); - - updateExtraSelections(); -} - -void -EditorProxy::requestDisableBlockSelection() noexcept -{ - const QPalette pal = widget->parentWidget() != nullptr ? widget->parentWidget()->palette() - : QApplication::palette(); - - blockSelection.clear(); - clearSelection.clear(); - widget->setPalette(pal); - - disconnect(widget, &QPlainTextEdit::selectionChanged, this, &EditorProxy::updateBlockSelection); - - updateExtraSelections(); -} - -void -EditorProxy::updateBlockSelection() noexcept -{ - requestSetBlockSelection(widget->textCursor()); -} - -void -EditorProxy::requestHasBlockSelection(bool *on) noexcept -{ - *on = !blockSelection.isEmpty(); -} - -void -EditorProxy::indentRegion(int beginBlock, int endBlock, QChar typedChar) noexcept -{ - QTextDocument *doc = widget->document(); - Q_ASSERT(doc); - - const int indentSize = static_cast<int>(fakeVimSettings()->shiftWidth.value()); - QTextBlock startBlock = doc->findBlockByNumber(beginBlock); - - // Record line lenghts for mark adjustments - QVector<int> lineLengths(endBlock - beginBlock + 1); - QTextBlock block = startBlock; - - for (int i = beginBlock; i <= endBlock; ++i) { - const QString line = block.text(); - lineLengths[i - beginBlock] = line.length(); - - if (typedChar.unicode() == 0 && line.simplified().isEmpty()) { - // clear empty lines - QTextCursor cursor(block); - while (!cursor.atBlockEnd()) - cursor.deleteChar(); - } - - else { - const QTextBlock previousBlock = block.previous(); - const QString previousLine = previousBlock.isValid() ? previousBlock.text() : QString(); - - int indent = firstNonSpace(previousLine); - if (typedChar == '}') - indent = std::max(0, indent - indentSize); - else if (previousLine.endsWith("{")) - indent += indentSize; - const QString indentString = QString(" ").repeated(indent); - - QTextCursor cursor(block); - cursor.beginEditBlock(); - cursor.movePosition(QTextCursor::StartOfBlock); - cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, - firstNonSpace(line)); - cursor.removeSelectedText(); - cursor.insertText(indentString); - cursor.endEditBlock(); - } - - block = block.next(); - } -} - -void -EditorProxy::checkForElectricCharacter(bool *result, QChar c) noexcept -{ - *result = c == '{' || c == '}'; -} - -int -EditorProxy::firstNonSpace(const QString &text) noexcept -{ - int indent = 0; - while (indent < text.length() && text.at(indent) == ' ') - ++indent; - return indent; -} - -void -EditorProxy::updateExtraSelections() noexcept -{ - widget->setExtraSelections(clearSelection + searchSelection + blockSelection); -} - -bool -EditorProxy::wantSaveAndQuit(const ExCommand &cmd) noexcept -{ - return cmd.cmd == "wq"; -} - -bool -EditorProxy::wantSave(const ExCommand &cmd) noexcept -{ - logInfo() << "Want to save the editor's file"; - return cmd.matches("w", "write") || cmd.matches("wa", "wall"); -} - -bool -EditorProxy::wantQuit(const ExCommand &cmd) noexcept -{ - logInfo() << "Want to quit editor"; - return cmd.matches("q", "quit") || cmd.matches("qa", "qall"); -} - -bool -EditorProxy::wantRun(const ExCommand &cmd) noexcept -{ - logInfo() << "Want to run a command: " << cmd.cmd; - return cmd.matches("run", "run") || cmd.matches("make", "make"); -} diff --git a/src/UI/ScriptViews/EditorProxy.hh b/src/UI/ScriptViews/EditorProxy.hh deleted file mode 100644 index 1ff5bdf9..00000000 --- a/src/UI/ScriptViews/EditorProxy.hh +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include "PreCompiledHeaders.hh" -#include "VivyApplication.hh" -#include "Lib/Log.hh" -#include "UI/ScriptViews/ScriptEditor.hh" - -namespace Vivy -{ -class EditorProxy; -class FakeVimHandler; -struct ExCommand; - -class EditorProxy final : public QObject { - Q_OBJECT - VIVY_UNMOVABLE_OBJECT(EditorProxy) - VIVY_APP_LOGGABLE_OBJECT(EditorProxy, logger) - - explicit EditorProxy(QPlainTextEdit *widget) noexcept; - -public: - ~EditorProxy() override; - -signals: - void handleInput(const QString &keys); - void requestSave(); - void requestSaveAndQuit(); - void requestQuit(); - void requestRun(); - -public slots: - void changeStatusData(const QString &info) noexcept; - void highlightMatches(const QString &pattern) noexcept; - void changeStatusMessage(const QString &contents, int cursorPos) noexcept; - void changeExtraInformation(const QString &info) noexcept; - void updateStatusBar() noexcept; - void handleExCommand(bool *handled, const ExCommand &cmd) noexcept; - void requestSetBlockSelection(const QTextCursor &tc) noexcept; - void requestDisableBlockSelection() noexcept; - void updateBlockSelection() noexcept; - void requestHasBlockSelection(bool *on) noexcept; - void indentRegion(int beginBlock, int endBlock, QChar typedChar) noexcept; - void checkForElectricCharacter(bool *result, QChar c) noexcept; - -private: - static int firstNonSpace(const QString &text) noexcept; - - void updateExtraSelections() noexcept; - bool wantSaveAndQuit(const ExCommand &cmd) noexcept; - bool wantSave(const ExCommand &cmd) noexcept; - bool wantQuit(const ExCommand &cmd) noexcept; - bool wantRun(const ExCommand &cmd) noexcept; - - QPlainTextEdit *widget; - QString statusMessage; - QString statusData; - - QList<QTextEdit::ExtraSelection> searchSelection; - QList<QTextEdit::ExtraSelection> clearSelection; - QList<QTextEdit::ExtraSelection> blockSelection; - -public: - static EditorProxy *connectSignals(FakeVimHandler *handler, QPlainTextEdit *editor) noexcept; -}; - -} diff --git a/src/UI/ScriptViews/ScriptEditor.cc b/src/UI/ScriptViews/ScriptEditor.cc deleted file mode 100644 index 6f7de9cf..00000000 --- a/src/UI/ScriptViews/ScriptEditor.cc +++ /dev/null @@ -1,173 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "UI/ScriptViews/ScriptEditor.hh" -#include "UI/ScriptViews/ScriptHighlighter.hh" - -using namespace Vivy; - -ScriptEditor::LineNumberArea::LineNumberArea(ScriptEditor *editor) noexcept - : QWidget(editor) - , scriptEditor(editor) -{ -} - -QSize -ScriptEditor::LineNumberArea::sizeHint() const noexcept -{ - return QSize(scriptEditor->lineNumberAreaWidth(), 0); -} - -void -ScriptEditor::LineNumberArea::paintEvent(QPaintEvent *event) noexcept -{ - scriptEditor->lineNumberAreaPaintEvent(event); -} - -ScriptEditor::ScriptEditor(QWidget *parent) noexcept - : QPlainTextEdit(parent) -{ - setStyleSheet(QStringLiteral("* {" - " background-color: #232629;" - " font-family: \"FiraCode\";" - " font-size: 10pt" - "}")); - lineNumberArea = new LineNumberArea(this); - setFrameShape(QFrame::NoFrame); - - connect(this, &ScriptEditor::blockCountChanged, this, &ScriptEditor::updateLineNumberAreaWidth); - connect(this, &ScriptEditor::updateRequest, this, &ScriptEditor::updateLineNumberArea); - - QTextCharFormat textFormat; - textFormat.setForeground(QBrush(Qt::white)); - mergeCurrentCharFormat(textFormat); - - QPlainTextEdit::setCursorWidth(0); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setBackgroundVisible(true); - updateLineNumberAreaWidth(0); - setObjectName(QStringLiteral("Editor")); - setFocus(); -} - -void -ScriptEditor::paintEvent(QPaintEvent *e) noexcept -{ - QPlainTextEdit::paintEvent(e); - - if (!cursorRect.isNull() && e->rect().intersects(cursorRect)) { - QRect rect = cursorRect; - cursorRect = QRect(); - QPlainTextEdit::viewport()->update(rect); - } - - // Draw text cursor. - QRect rect = QPlainTextEdit::cursorRect(); - if (e->rect().intersects(rect)) { - QPainter painter(QPlainTextEdit::viewport()); - - if (QPlainTextEdit::overwriteMode()) { - QFontMetrics fm(QPlainTextEdit::font()); - const int position = QPlainTextEdit::textCursor().position(); - const QChar c = QPlainTextEdit::document()->characterAt(position); - rect.setWidth(fm.horizontalAdvance(c)); - painter.setPen(Qt::NoPen); - painter.setBrush(QPlainTextEdit::palette().color(QPalette::Base)); - painter.setCompositionMode(QPainter::CompositionMode_Difference); - } else { - rect.setWidth(QPlainTextEdit::cursorWidth()); - painter.setPen(QPlainTextEdit::palette().color(QPalette::Text)); - } - - painter.drawRect(rect); - cursorRect = rect; - } -} - -void -ScriptEditor::keyPressEvent(QKeyEvent *e) noexcept -{ - if (e->key() == Qt::Key_Tab) { - QTextCursor cursor = textCursor(); - cursor.insertText(spacesForTab); - e->accept(); - } - - else { - QPlainTextEdit::keyPressEvent(e); - } -} - -int -ScriptEditor::lineNumberAreaWidth() noexcept -{ - int digits = 1; - int max = qMax(1, blockCount()); - while (max >= 10) { - max /= 10; - ++digits; - } - if (digits == 1) - digits++; - - const int space = 3 + fontMetrics().horizontalAdvance('9') * digits; - return space; -} - -void -ScriptEditor::updateLineNumberAreaWidth([[maybe_unused]] int newBlockCount) noexcept -{ - setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); -} - -void -ScriptEditor::updateLineNumberArea(const QRect &rect, int dy) noexcept -{ - if (dy) - lineNumberArea->scroll(0, dy); - else - lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); - - if (rect.contains(viewport()->rect())) - updateLineNumberAreaWidth(0); -} - -void -ScriptEditor::resizeEvent(QResizeEvent *e) noexcept -{ - QPlainTextEdit::resizeEvent(e); - const QRect cr = contentsRect(); - lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); -} - -void -ScriptEditor::lineNumberAreaPaintEvent(QPaintEvent *event) noexcept -{ - QPainter painter(lineNumberArea); - painter.fillRect(event->rect(), QColor::fromRgb(49, 54, 59)); - QTextBlock block = firstVisibleBlock(); - int blockNumber = block.blockNumber(); - int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top()); - int bottom = top + qRound(blockBoundingRect(block).height()); - const int current = textCursor().blockNumber(); - - while (block.isValid() && top <= event->rect().bottom()) { - if (block.isVisible() && bottom >= event->rect().top()) { - const bool drawCurrent = blockNumber == current; - const QString number = - drawCurrent ? QStringLiteral("->") : QString::number(blockNumber + 1); - painter.setPen(drawCurrent ? Qt::white : Qt::black); - painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), - Qt::AlignRight, number); - } - - block = block.next(); - top = bottom; - bottom = top + qRound(blockBoundingRect(block).height()); - ++blockNumber; - } -} - -void -ScriptEditor::updateLastLuaError(int line, QString desc) -{ - logDebug() << "Update error on line " << line << " with description " << desc; -} diff --git a/src/UI/ScriptViews/ScriptEditor.hh b/src/UI/ScriptViews/ScriptEditor.hh deleted file mode 100644 index f9afe789..00000000 --- a/src/UI/ScriptViews/ScriptEditor.hh +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#ifndef __cplusplus -#error "This is a C++ header" -#endif - -#include "PreCompiledHeaders.hh" -#include "VivyApplication.hh" -#include "Lib/Log.hh" -#include "Lib/Utils.hh" - -namespace Vivy -{ -class ScriptEditor final : public QPlainTextEdit { - Q_OBJECT - VIVY_UNMOVABLE_OBJECT(ScriptEditor) - VIVY_APP_LOGGABLE_OBJECT(ScriptEditor, logger) - - // Get the line numbers, private class - class LineNumberArea final : public QWidget { - VIVY_UNMOVABLE_OBJECT(LineNumberArea) - public: - LineNumberArea(ScriptEditor *editor) noexcept; - - QSize sizeHint() const noexcept override; - - protected: - void paintEvent(QPaintEvent *event) noexcept override; - - private: - ScriptEditor *scriptEditor{ nullptr }; - }; - - // Number of spaces in a tab - static constexpr int spacesPerTab = 4; - static inline const QString spacesForTab = QString(QStringLiteral(" ")).repeated(spacesPerTab); - -public: - ScriptEditor(QWidget *parent) noexcept; - - void lineNumberAreaPaintEvent(QPaintEvent *event) noexcept; - int lineNumberAreaWidth() noexcept; - -public slots: - void updateLastLuaError(int, QString); - -protected: - void resizeEvent(QResizeEvent *) noexcept override; - void keyPressEvent(QKeyEvent *) noexcept override; - void paintEvent(QPaintEvent *) noexcept override; - -private slots: - void updateLineNumberAreaWidth(int newBlockCount) noexcept; - void updateLineNumberArea(const QRect &rect, int dy) noexcept; - -private: - QWidget *lineNumberArea{ nullptr }; - QRect cursorRect{}; -}; -} diff --git a/src/UI/ScriptViews/ScriptHighlighter.cc b/src/UI/ScriptViews/ScriptHighlighter.cc deleted file mode 100644 index 29e665e8..00000000 --- a/src/UI/ScriptViews/ScriptHighlighter.cc +++ /dev/null @@ -1,172 +0,0 @@ -#include "PreCompiledHeaders.hh" -#include "UI/ScriptViews/ScriptHighlighter.hh" -#include "UI/Theme/Theme.hh" -#include "VivyApplication.hh" -#include "Lib/Utils.hh" - -using namespace Vivy; - -ScriptHighlighter::HighlightingRule::HighlightingRule(QRegExp pttrn, QTextCharFormat frmt) - : pattern(pttrn) - , format(frmt) -{ -} - -void -ScriptHighlighter::resetHighlightingRule() noexcept -{ - highlightingRules.clear(); - const Theme::HighlightingTheme &theme = vivyApp->getTheme()->getHighlightingTheme(); - - // function calls - functionFormat.setForeground(theme.functionForeground); - highlightingRules.emplace_back(QRegExpLiteral("\\b[A-Za-z0-9_]+[ ]*(?=\\()"), functionFormat); - highlightingRules.emplace_back(QRegExpLiteral("\\b[A-Za-z0-9_]+[ ]*(?=\\{)"), functionFormat); - - // Member and enum members - enumFormat.setForeground(theme.enumForeground); - enumFormat.setFontWeight(QFont::Bold); - memberFormat.setForeground(theme.memberForeground); - memberFormat.setFontWeight(QFont::StyleItalic); - highlightingRules.emplace_back(QRegExpLiteral("\\.[a-z][\\dA-Za-z]*\\b"), memberFormat); - highlightingRules.emplace_back(QRegExpLiteral("\\b[A-Z][\\dA-Z_]*\\b"), enumFormat); - - // keywords - const QStringList keywordPatterns = { - QStringLiteral("\\bfunction\\b"), QStringLiteral("\\bbreak\\b"), - QStringLiteral("\\bgoto\\b"), QStringLiteral("\\bdo\\b"), - QStringLiteral("\\bend\\b"), QStringLiteral("\\bwhile\\b"), - QStringLiteral("\\brepeat\\b"), QStringLiteral("\\buntil\\b"), - QStringLiteral("\\bif\\b"), QStringLiteral("\\bthen\\b"), - QStringLiteral("\\belseif\\b"), QStringLiteral("\\belse\\b"), - QStringLiteral("\\bfor\\b"), QStringLiteral("\\bin\\b"), - QStringLiteral("\\blocal\\b"), QStringLiteral("\\bor\\b"), - QStringLiteral("\\band\\b"), QStringLiteral("\\bnot\\b"), - QStringLiteral("\\breturn\\b"), QStringLiteral("\\b\\=\\b"), - QStringLiteral("\\b\\+\\=\\b"), QStringLiteral("\\b\\-\\=\\b"), - QStringLiteral("\\b\\*\\=\\b"), QStringLiteral("\\b\\/\\=\\b"), - }; - - keywordFormat.setForeground(theme.keywordForeground); - keywordFormat.setFontWeight(QFont::Bold); - - for (QString const &pattern : keywordPatterns) - highlightingRules.emplace_back(QRegExp(pattern), keywordFormat); - - // numbers, boolean, nil - const QStringList valuePatterns = { - QStringLiteral("\\bnil\\b"), - QStringLiteral("\\btrue\\b"), - QStringLiteral("\\bfalse\\b"), - QStringLiteral("\\b\\d+\\b"), - QStringLiteral("\\b\\d+.\\b"), - QStringLiteral("\\b\\d+e\\b"), - QStringLiteral("\\b\\[\\dA-Fa-F]+\\b"), - }; - - valueFormat.setForeground(theme.valueForeground); - valueFormat.setFontWeight(QFont::Normal); - - for (QString const &pattern : valuePatterns) - highlightingRules.emplace_back(QRegExp(pattern), valueFormat); - - // strings - quotationFormat.setForeground(theme.valueForeground); - highlightingRules.emplace_back(QRegExpLiteral("\"[^\"]*\""), quotationFormat); - highlightingRules.emplace_back(QRegExpLiteral("\'[^\']*\'"), quotationFormat); - quoteStartExpression = QRegExpLiteral("\\[\\["); - quoteEndExpression = QRegExpLiteral("\\]\\]"); - - // comments - singleLineCommentFormat.setForeground(theme.commentForeground); - highlightingRules.emplace_back(QRegExpLiteral("--[^\n]*"), singleLineCommentFormat); - commentStartExpression = QRegExpLiteral("--\\[\\["); - commentEndExpression = QRegExpLiteral("\\]\\]"); -} - -ScriptHighlighter::ScriptHighlighter(QTextDocument *parent) noexcept - : QSyntaxHighlighter(parent) -{ - resetHighlightingRule(); -} - -void -ScriptHighlighter::setCurrentBlockState(const ScriptHighlighter::BlockState state) noexcept -{ - QSyntaxHighlighter::setCurrentBlockState(Utils::toUnderlying(state)); -} - -ScriptHighlighter::BlockState -ScriptHighlighter::previousBlockState() noexcept -{ - const int state = QSyntaxHighlighter::previousBlockState(); - if (state != Utils::toUnderlying(BlockState::Quote) && - state != Utils::toUnderlying(BlockState::Comment)) - return BlockState::None; - - return static_cast<BlockState>(state); -} - -void -ScriptHighlighter::highlightBlock(const QString &text) noexcept -{ - for (const HighlightingRule &rule : highlightingRules) { - QRegExp expression(rule.pattern); - int index = expression.indexIn(text); - while (index >= 0) { - const int length = expression.matchedLength(); - setFormat(index, length, rule.format); - index = expression.indexIn(text, index + length); - } - } - - setCurrentBlockState(BlockState::None); - const BlockState previousState = previousBlockState(); - - highlightStringBlock(text, previousState); - highlightCommentBlock(text, previousState); -} - -void -ScriptHighlighter::highlightBlock(const QString &text, const BlockState previousState, - const BlockState toHighlight, const QRegExp &startExpr, - const QRegExp &endExpr, const QTextCharFormat &format) noexcept -{ - int start = -1; - if (previousState == toHighlight) { - start = 0; - } else if (previousState == BlockState::None) { - start = startExpr.indexIn(text); - } - - while (start >= 0) { - const int end = endExpr.indexIn(text, start); - int length; - - if (end == -1) { - setCurrentBlockState(toHighlight); - length = text.length() - start; - } else { - length = end - start + endExpr.matchedLength(); - } - - setFormat(start, length, format); - start = startExpr.indexIn(text, start + length); - } -} - -void -ScriptHighlighter::highlightStringBlock(const QString &text, - const BlockState previousState) noexcept -{ - highlightBlock(text, previousState, BlockState::Quote, quoteStartExpression, quoteEndExpression, - quotationFormat); -} - -void -ScriptHighlighter::highlightCommentBlock(const QString &text, - const BlockState previousState) noexcept -{ - highlightBlock(text, previousState, BlockState::Comment, commentStartExpression, - commentEndExpression, singleLineCommentFormat); -} diff --git a/src/UI/ScriptViews/ScriptHighlighter.hh b/src/UI/ScriptViews/ScriptHighlighter.hh deleted file mode 100644 index 3d30a340..00000000 --- a/src/UI/ScriptViews/ScriptHighlighter.hh +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once - -#ifndef __cplusplus -#error "This is a C++ header" -#endif - -#include "PreCompiledHeaders.hh" -#include "UI/Theme/Theme.hh" - -namespace Vivy -{ -class ScriptHighlighter final : public QSyntaxHighlighter { - Q_OBJECT - - struct HighlightingRule { - HighlightingRule(QRegExp pttrn, QTextCharFormat frmt); - - QRegExp pattern; - QTextCharFormat format; - }; - - enum class BlockState { None = -1, Quote = 1, Comment = 2 }; - -public: - ScriptHighlighter(QTextDocument *parent = nullptr) noexcept; - -protected: - void highlightBlock(const QString &text) noexcept override; - - void setCurrentBlockState(const BlockState) noexcept; - BlockState previousBlockState() noexcept; - -private: - void highlightStringBlock(const QString &text, const BlockState) noexcept; - void highlightCommentBlock(const QString &text, const BlockState) noexcept; - - void highlightBlock(const QString &text, const BlockState previous, - const BlockState toHighlight, const QRegExp &start, const QRegExp &end, - const QTextCharFormat &format) noexcept; - - void resetHighlightingRule() noexcept; - - std::vector<HighlightingRule> highlightingRules; - - QRegExp commentStartExpression; - QRegExp commentEndExpression; - QRegExp quoteStartExpression; - QRegExp quoteEndExpression; - - QTextCharFormat keywordFormat; - QTextCharFormat valueFormat; - QTextCharFormat singleLineCommentFormat; - QTextCharFormat quotationFormat; - QTextCharFormat functionFormat; - QTextCharFormat enumFormat; - QTextCharFormat memberFormat; -}; -} diff --git a/src/VivyApplication.cc b/src/VivyApplication.cc index f37e95cd..aaee4ad0 100644 --- a/src/VivyApplication.cc +++ b/src/VivyApplication.cc @@ -6,8 +6,6 @@ #include "UI/Theme/Theme.hh" #include "Lib/Document/VivyDocumentStore.hh" #include "Lib/Document/VivyDocument.hh" -#include "Lib/Script/ScriptStore.hh" -#include "Lib/Script/ScriptDocument.hh" using namespace Vivy; @@ -15,7 +13,7 @@ VivyApplication::VivyApplication(int &argc, char **argv) : QApplication(argc, argv) { documentStore = std::make_shared<VivyDocumentStore>(); - scriptStore = std::make_shared<ScriptStore>(); + //scriptStore = std::make_shared<ScriptStore>(); VIVY_LOG_CTOR() << "Construction is OK"; if (argc >= 2) { @@ -27,10 +25,10 @@ VivyApplication::VivyApplication(int &argc, char **argv) if (passedFileType == Utils::DocumentType::Vivy) { selectedVivyDoc = documentStore->loadDocument(passedFileName); logInfo() << "Select vivy document " << passedFileName; - } else if (passedFileType == Utils::DocumentType::VivyScript) { + } /* else if (passedFileType == Utils::DocumentType::VivyScript) { selectedScriptDoc = scriptStore->loadDocument(passedFileName); logInfo() << "Select script document " << passedFileName; - } else { + } */ else { logError() << "Not handled file type for file " << passedFileName; } } else { @@ -96,13 +94,13 @@ VivyApplication::exec() noexcept if ((selectedVivyDoc == nullptr) || (selectedScriptDoc == nullptr)) return 1; - if (!scriptStore->executeScript(selectedScriptDoc->getUuid(), selectedVivyDoc)) - return 2; + //if (!scriptStore->executeScript(selectedScriptDoc->getUuid(), selectedVivyDoc)) + // return 2; - for (const auto &str : scriptStore->getLoadedModules()) { - std::cout << "Module " << str << " was loaded!\n"; - [[maybe_unused]] const auto *mod = scriptStore->getModule(str); - } + //for (const auto &str : scriptStore->getLoadedModules()) { + // std::cout << "Module " << str << " was loaded!\n"; + // [[maybe_unused]] const auto *mod = scriptStore->getModule(str); + //} return 0; } -- GitLab