ConsoleObject.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "ConsoleObject.h"
  2. #include <cstdlib>
  3. #include "EngineObject.h"
  4. #include "ScriptEngine.h"
  5. #include "WallpaperEngine/Data/Utils/ScopeGuard.h"
  6. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  7. using namespace WallpaperEngine::Scripting;
  8. // wallpaper scripts often console.log every frame, WE only shows that in its editor console
  9. JSValue console_log (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
  10. static const bool enabled = std::getenv ("LWE_SCRIPT_LOG") != nullptr;
  11. if (!enabled || argc < 1) {
  12. return JS_UNDEFINED;
  13. }
  14. std::stringstream stream;
  15. for (int i = 0; i < argc; i++) {
  16. const char* str = JS_ToCString (ctx, argv[i]);
  17. ScopeGuard guard ([ctx, str] { JS_FreeCString (ctx, str); });
  18. stream << str;
  19. }
  20. sLog.out (stream.str ());
  21. return JS_UNDEFINED;
  22. }
  23. JSValue console_error (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
  24. if (argc < 1) {
  25. return JS_UNDEFINED;
  26. }
  27. std::stringstream stream;
  28. for (int i = 0; i < argc; i++) {
  29. const char* str = JS_ToCString (ctx, argv[i]);
  30. ScopeGuard guard ([ctx, str] { JS_FreeCString (ctx, str); });
  31. stream << str;
  32. }
  33. sLog.error (stream.str ());
  34. return JS_UNDEFINED;
  35. }
  36. ConsoleObject::ConsoleObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene) :
  37. m_scene (scene), m_engine (engine), m_classId (0) {
  38. this->m_definition = { .class_name = "IConsole" };
  39. JS_NewClassID (this->m_engine.getRuntime (), &this->m_classId);
  40. JS_NewClass (this->m_engine.getRuntime (), this->m_classId, &this->m_definition);
  41. this->m_instance = JS_NewObjectClass (this->m_engine.getContext (), this->m_classId);
  42. JS_DupValue (this->m_engine.getContext (), this->m_instance);
  43. JS_SetOpaque (this->m_instance, this);
  44. JS_DefinePropertyValueStr (
  45. this->m_engine.getContext (), this->m_instance, "log",
  46. JS_NewCFunction (this->m_engine.getContext (), console_log, "log", 1), JS_PROP_C_W_E
  47. );
  48. JS_DefinePropertyValueStr (
  49. this->m_engine.getContext (), this->m_instance, "error",
  50. JS_NewCFunction (this->m_engine.getContext (), console_error, "error", 1), JS_PROP_C_W_E
  51. );
  52. }
  53. ConsoleObject::~ConsoleObject () { JS_FreeValue (this->m_engine.getContext (), this->m_instance); }