ScriptEngine.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. #include "ScriptEngine.h"
  2. #include "WallpaperEngine/Media/ThumbnailPalette.h"
  3. #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
  4. #include "Adapters/ScriptableObjectAdapter.h"
  5. #include "JS.h"
  6. #include "ScriptPropertiesObject.h"
  7. #include "ScriptableObject.h"
  8. #include "WallpaperEngine/Audio/AudioContext.h"
  9. #include "WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h"
  10. #include "WallpaperEngine/Data/Model/Property.h"
  11. #include "WallpaperEngine/Desktop/UserShortcut.h"
  12. #include "WallpaperEngine/Logging/Log.h"
  13. #include "WallpaperEngine/Render/CObject.h"
  14. #include "WallpaperEngine/Render/Objects/CImage.h"
  15. #include "WallpaperEngine/Render/Objects/CSound.h"
  16. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  17. #include "WallpaperEngine/Scripting/Builtins.generated.h"
  18. #include <libplatform/libplatform.h>
  19. #include <algorithm>
  20. #include <array>
  21. #include <cctype>
  22. #include <cerrno>
  23. #include <chrono>
  24. #include <cmath>
  25. #include <cstdio>
  26. #include <cstring>
  27. #include <ctime>
  28. #include <filesystem>
  29. #include <future>
  30. #include <optional>
  31. #include <ranges>
  32. #include <sstream>
  33. #include <string_view>
  34. #include <vector>
  35. namespace WallpaperEngine::Render::Objects {
  36. class CSound;
  37. }
  38. using namespace WallpaperEngine::Scripting;
  39. using namespace WallpaperEngine::Data::Model;
  40. extern float g_Time;
  41. extern float g_TimeLast;
  42. std::optional<std::string> ScriptEngine::readScriptAsset (const std::string& path) const {
  43. try {
  44. return this->m_scene.getAssetLocator ().readString (path);
  45. } catch (std::filesystem::filesystem_error& e) {
  46. sLog.error ("ScriptEngine: cannot read ", path, ": ", e.what ());
  47. return std::nullopt;
  48. }
  49. }
  50. namespace {
  51. v8::MaybeLocal<v8::Module> resolveModule (
  52. v8::Local<v8::Context> context, v8::Local<v8::String> specifier, v8::Local<v8::FixedArray>, v8::Local<v8::Module>
  53. ) {
  54. auto* isolate = v8::Isolate::GetCurrent ();
  55. return ScriptEngine::from (isolate).importModule (JS::toString (isolate, specifier));
  56. }
  57. } // namespace
  58. // same lookup as scenescript64: the import name lowercased under scripts/jsmodules/, ".js" appended
  59. // unless the name already has it ('WEMath' -> scripts/jsmodules/wemath.js). Every import of a name gets the same
  60. // module, the resolver (sub_1816469C0) keeps them in a map keyed by the lowercased name
  61. v8::MaybeLocal<v8::Module> ScriptEngine::importModule (const std::string& specifier) {
  62. std::string name (specifier);
  63. std::ranges::transform (name, name.begin (), [] (unsigned char c) { return std::tolower (c); });
  64. if (const auto it = this->m_imports.find (name); it != this->m_imports.end ()) {
  65. return it->second.Get (this->m_isolate);
  66. }
  67. std::string path = "scripts/jsmodules/" + name;
  68. if (name.find (".js") == std::string::npos) {
  69. path += ".js";
  70. }
  71. const auto source = this->readScriptAsset (path);
  72. if (!source.has_value ()) {
  73. JS::throwReferenceError (this->m_isolate, "could not load module '" + specifier + "'");
  74. return {};
  75. }
  76. v8::ScriptCompiler::Source compileSource (
  77. JS::string (this->m_isolate, *source), JS::origin (this->m_isolate, specifier, true)
  78. );
  79. v8::Local<v8::Module> module;
  80. if (!v8::ScriptCompiler::CompileModule (this->m_isolate, &compileSource).ToLocal (&module)) {
  81. return {};
  82. }
  83. // V8 instantiates and evaluates it along with the module importing it
  84. this->m_imports[name].Reset (this->m_isolate, module);
  85. return module;
  86. }
  87. v8::Local<v8::Value> ScriptEngine::dynamicToJs (DynamicValue& value) const {
  88. switch (value.getType ()) {
  89. case DynamicValue::Null:
  90. return v8::Null (this->m_isolate);
  91. case DynamicValue::String:
  92. return JS::string (this->m_isolate, value.getString ());
  93. case DynamicValue::Float:
  94. return v8::Number::New (this->m_isolate, value.getFloat ());
  95. case DynamicValue::Int:
  96. return v8::Integer::New (this->m_isolate, value.getInt ());
  97. case DynamicValue::Boolean:
  98. return v8::Boolean::New (this->m_isolate, value.getBool ());
  99. case DynamicValue::Vec2:
  100. return this->m_adapters.vec2->instantiate (value);
  101. case DynamicValue::Vec3:
  102. return this->m_adapters.vec3->instantiate (value);
  103. case DynamicValue::Vec4:
  104. return this->m_adapters.vec4->instantiate (value);
  105. default:
  106. return v8::Undefined (this->m_isolate);
  107. }
  108. }
  109. bool ScriptEngine::hasScript (const DynamicValue& value) const {
  110. return std::ranges::any_of (this->m_scriptModules, [&value] (const auto& entry) {
  111. return &entry.second.value == &value;
  112. });
  113. }
  114. v8::Local<v8::Value> ScriptEngine::userPropertyToJs (Property& property) const {
  115. // same shape the real engine hands scripts (jsclasses/baseclasses.js), never the command itself
  116. if (property.is<PropertyUserShortcut> ()) {
  117. const auto shortcut = Desktop::UserShortcut::parse (property.getString ());
  118. v8::Local<v8::Object> result = v8::Object::New (this->m_isolate);
  119. JS::set (this->getContext (), result, "isbound", v8::Boolean::New (this->m_isolate, shortcut.has_value ()));
  120. return result;
  121. }
  122. if (property.is<PropertyColor> () && property.getType () == DynamicValue::Vec4) {
  123. DynamicValue rgb (glm::vec3 (property.getVec4 ()));
  124. return this->m_adapters.vec3->instantiate (rgb);
  125. }
  126. return this->dynamicToJs (property);
  127. }
  128. // real WE spreads a number returned for a vector property over every component and the property stays a
  129. // vector, so the next update() still gets a Vec
  130. static bool updateVectorFromNumber (DynamicValue& source, float number) {
  131. switch (source.getType ()) {
  132. case DynamicValue::Vec4:
  133. source.update (glm::vec4 (number), DynamicValue::UpdateSource::Script);
  134. return true;
  135. case DynamicValue::Vec3:
  136. source.update (glm::vec3 (number), DynamicValue::UpdateSource::Script);
  137. return true;
  138. case DynamicValue::Vec2:
  139. source.update (glm::vec2 (number), DynamicValue::UpdateSource::Script);
  140. return true;
  141. default:
  142. return false;
  143. }
  144. }
  145. static bool jsToDynamicValue (v8::Isolate* isolate, v8::Local<v8::Value> val, DynamicValue& source) {
  146. // update()'s contract is "return the new value"; falling off the end of a function (or an
  147. // early "if (cond) return x;" with no else) yields undefined and is meant as "nothing to
  148. // change this frame", not "reset this property to zero" - DynamicValue::update(source) with
  149. // no value does the latter (it's meant for genuinely-null JSON properties at parse time, see
  150. // DynamicValueParser), and calling it here would zero out (e.g. scale -> 0, i.e. invisible)
  151. // any property whose script doesn't explicitly return on every path.
  152. if (val.IsEmpty () || val->IsNullOrUndefined ()) {
  153. return false;
  154. }
  155. const auto context = isolate->GetCurrentContext ();
  156. if (val->IsInt32 ()) {
  157. const int32_t number = val.As<v8::Int32> ()->Value ();
  158. // the property keeps its own type (scenescript64 sub_181620E10), "alpha = 1" leaves alpha a float
  159. if (source.getType () == DynamicValue::Float) {
  160. source.update (static_cast<float> (number), DynamicValue::UpdateSource::Script);
  161. } else if (!updateVectorFromNumber (source, static_cast<float> (number))) {
  162. source.update (number, DynamicValue::UpdateSource::Script);
  163. }
  164. return true;
  165. }
  166. if (val->IsBoolean ()) {
  167. source.update (val->IsTrue (), DynamicValue::UpdateSource::Script);
  168. return true;
  169. }
  170. if (val->IsNumber ()) {
  171. const auto number = static_cast<float> (val.As<v8::Number> ()->Value ());
  172. if (!updateVectorFromNumber (source, number)) {
  173. source.update (number, DynamicValue::UpdateSource::Script);
  174. }
  175. return true;
  176. }
  177. if (val->IsString ()) {
  178. source.update (JS::toString (isolate, val), DynamicValue::UpdateSource::Script);
  179. return true;
  180. }
  181. if (val->IsObject ()) {
  182. const v8::Local<v8::Value> x = JS::get (context, val, "x");
  183. const v8::Local<v8::Value> y = JS::get (context, val, "y");
  184. const v8::Local<v8::Value> z = JS::get (context, val, "z");
  185. const v8::Local<v8::Value> w = JS::get (context, val, "w");
  186. // runs every frame, a bad value from one script must not take the whole wallpaper down
  187. if (!x->IsNumber () || !y->IsNumber ()) {
  188. static bool reported = false;
  189. if (!reported) {
  190. reported = true;
  191. sLog.error ("Script returned a vector without numeric x and y components, keeping the previous value");
  192. }
  193. return false;
  194. }
  195. const double xVal = x.As<v8::Number> ()->Value ();
  196. const double yVal = y.As<v8::Number> ()->Value ();
  197. if (!z->IsNumber ()) {
  198. source.update (glm::vec2 (xVal, yVal), DynamicValue::UpdateSource::Script);
  199. return true;
  200. }
  201. const double zVal = z.As<v8::Number> ()->Value ();
  202. if (!w->IsNumber ()) {
  203. source.update (glm::vec3 (xVal, yVal, zVal), DynamicValue::UpdateSource::Script);
  204. return true;
  205. }
  206. source.update (glm::vec4 (xVal, yVal, zVal, w.As<v8::Number> ()->Value ()), DynamicValue::UpdateSource::Script);
  207. return true;
  208. }
  209. return false;
  210. }
  211. void ScriptEngine::assignJsValue (v8::Local<v8::Value> val, DynamicValue& target) const {
  212. jsToDynamicValue (this->m_isolate, val, target);
  213. }
  214. // Objects keep "angles" in radians, scripts get degrees: scenescript64 2.8.42 converts every property whose
  215. // descriptor has flag 4 on the way in (sub_1816208E0, * 57.29578) and out (sub_181620E10, * 0.017453292), and
  216. // wallpaper64 only sets that flag on the object "angles" property (sub_1401E0530)
  217. static bool isDegreeProperty (std::string_view name) { return name == "angles"; }
  218. static DynamicValue scaledAngles (const DynamicValue& value, float factor) {
  219. switch (value.getType ()) {
  220. case DynamicValue::Float:
  221. return DynamicValue (value.getFloat () * factor);
  222. case DynamicValue::Vec2:
  223. return DynamicValue (value.getVec2 () * factor);
  224. case DynamicValue::Vec3:
  225. return DynamicValue (value.getVec3 () * factor);
  226. case DynamicValue::Vec4:
  227. return DynamicValue (value.getVec4 () * factor);
  228. default:
  229. return value;
  230. }
  231. }
  232. v8::Local<v8::Value> ScriptEngine::propertyToJs (DynamicValue& value, std::string_view name) const {
  233. if (!isDegreeProperty (name)) {
  234. return this->dynamicToJs (value);
  235. }
  236. DynamicValue degrees = scaledAngles (value, 57.29578f);
  237. return this->dynamicToJs (degrees);
  238. }
  239. // scenescript64 (sub_181620E10, used for property scripts and layer setters) converts by the property's type and
  240. // drops a value of the wrong kind: bool properties only take IsBoolean, int/float ones only IsNumber.
  241. // 3509578940's battery fill returns a number from its visible script and stays visible in WE
  242. static bool matchesPropertyType (v8::Local<v8::Value> val, const DynamicValue& target) {
  243. switch (target.getType ()) {
  244. case DynamicValue::Boolean:
  245. return val->IsBoolean ();
  246. case DynamicValue::Int:
  247. case DynamicValue::Float:
  248. return val->IsNumber ();
  249. default:
  250. return true;
  251. }
  252. }
  253. void ScriptEngine::assignPropertyJsValue (v8::Local<v8::Value> val, DynamicValue& target, std::string_view name) const {
  254. if (val.IsEmpty () || !matchesPropertyType (val, target)) {
  255. return;
  256. }
  257. // scenescript64 (sub_181620E10, string descriptors) stores ToString of whatever the script assigns, only
  258. // undefined/null are ignored: 3577513994 sets a text layer to getDate()'s number
  259. if (target.getType () == DynamicValue::String && !val->IsString () && !val->IsNullOrUndefined ()) {
  260. v8::TryCatch tryCatch (this->m_isolate);
  261. v8::Local<v8::String> text;
  262. if (val->ToString (this->getContext ()).ToLocal (&text)) {
  263. target.update (JS::toString (this->m_isolate, text), DynamicValue::UpdateSource::Script);
  264. }
  265. return;
  266. }
  267. if (!isDegreeProperty (name)) {
  268. jsToDynamicValue (this->m_isolate, val, target);
  269. return;
  270. }
  271. DynamicValue degrees = scaledAngles (target, 57.29578f);
  272. if (!jsToDynamicValue (this->m_isolate, val, degrees)) {
  273. return;
  274. }
  275. const DynamicValue radians = scaledAngles (degrees, 0.017453292f);
  276. switch (radians.getType ()) {
  277. case DynamicValue::Float:
  278. target.update (radians.getFloat (), DynamicValue::UpdateSource::Script);
  279. break;
  280. case DynamicValue::Vec2:
  281. target.update (radians.getVec2 (), DynamicValue::UpdateSource::Script);
  282. break;
  283. case DynamicValue::Vec3:
  284. target.update (radians.getVec3 (), DynamicValue::UpdateSource::Script);
  285. break;
  286. case DynamicValue::Vec4:
  287. target.update (radians.getVec4 (), DynamicValue::UpdateSource::Script);
  288. break;
  289. default:
  290. target.update (radians, DynamicValue::UpdateSource::Script);
  291. break;
  292. }
  293. }
  294. ScriptEngine::Scope::Scope (const ScriptEngine& engine) :
  295. m_isolateScope (engine.m_isolate), m_handleScope (engine.m_isolate),
  296. m_contextScope (engine.m_context.Get (engine.m_isolate)) { }
  297. // one isolate and context per scene, like scenescript64's engine (sub_181647AA0)
  298. ScriptEngine::ScriptEngine (Wallpapers::CScene& scene, Media::MediaSource& mediaSource) :
  299. m_scene (scene), m_mediaSource (mediaSource) {
  300. this->m_unregisterMediaUpdateCallback
  301. = mediaSource.addMetadataListener ([this] (const Media::MediaSource::MediaInfo& info) {
  302. this->notifyMediaUpdate (info);
  303. });
  304. this->m_unregisterAlbumArtUpdateCallback
  305. = mediaSource.addAlbumArtListener ([this] (const Media::MediaSource::MediaInfo& info) {
  306. // TODO: SEPARATE THESE INTO THEIR OWN UPDATES SO JS ONLY RECEIVES THE MEANINGFUL UPDATES
  307. this->notifyMediaUpdate (info);
  308. });
  309. JS::platform ();
  310. this->m_allocator.reset (v8::ArrayBuffer::Allocator::NewDefaultAllocator ());
  311. v8::Isolate::CreateParams params;
  312. params.array_buffer_allocator = this->m_allocator.get ();
  313. this->m_isolate = v8::Isolate::New (params);
  314. this->m_isolate->SetData (0, this);
  315. const v8::Isolate::Scope isolateScope (this->m_isolate);
  316. const v8::HandleScope handleScope (this->m_isolate);
  317. const v8::Local<v8::Context> context = v8::Context::New (this->m_isolate);
  318. const v8::Context::Scope contextScope (context);
  319. this->m_context.Reset (this->m_isolate, context);
  320. // WE's own Vec2/Vec3/Vec4/Mat3/Mat4 classes, the natives below only create instances of them
  321. if (const auto baseClasses = this->readScriptAsset ("scripts/jsclasses/baseclasses.js"); baseClasses.has_value ()) {
  322. this->evaluateGlobalScript (*baseClasses, "baseclasses.js");
  323. }
  324. this->m_adapters = {
  325. .vec4 = std::make_unique<Adapters::VectorAdapter<4>> (*this),
  326. .vec3 = std::make_unique<Adapters::VectorAdapter<3>> (*this),
  327. .vec2 = std::make_unique<Adapters::VectorAdapter<2>> (*this),
  328. .object = std::make_unique<Adapters::ScriptableObjectAdapter> (*this),
  329. };
  330. this->m_engineObject = std::make_unique<EngineObject> (*this, scene);
  331. this->m_inputObject = std::make_unique<InputObject> (*this, scene);
  332. this->m_sceneObject = std::make_unique<SceneObject> (*this, scene);
  333. this->m_consoleObject = std::make_unique<ConsoleObject> (*this, scene);
  334. this->m_scriptPropertiesObject = std::make_unique<ScriptPropertiesObject> (*this, scene);
  335. this->installBuiltins ();
  336. const v8::Local<v8::Object> global = context->Global ();
  337. JS::define (context, global, "engine", this->m_engineObject->getInstance ());
  338. JS::define (context, global, "input", this->m_inputObject->getInstance ());
  339. JS::define (context, global, "thisScene", this->m_sceneObject->getInstance ());
  340. JS::define (context, global, "console", this->m_consoleObject->getInstance ());
  341. JS::define (context, global, "shared", v8::Object::New (this->m_isolate));
  342. }
  343. ScriptEngine::~ScriptEngine () {
  344. this->m_unregisterMediaUpdateCallback ();
  345. this->m_unregisterAlbumArtUpdateCallback ();
  346. // every handle has to go before the isolate does
  347. this->m_scriptModules.clear ();
  348. this->m_videoEndedCallbacks.clear ();
  349. this->m_animationLayerEndedCallbacks.clear ();
  350. this->m_imports.clear ();
  351. this->m_consoleObject.reset ();
  352. this->m_engineObject.reset ();
  353. this->m_inputObject.reset ();
  354. this->m_sceneObject.reset ();
  355. this->m_scriptPropertiesObject.reset ();
  356. this->m_adapters.vec4.reset ();
  357. this->m_adapters.vec3.reset ();
  358. this->m_adapters.vec2.reset ();
  359. this->m_adapters.object.reset ();
  360. this->m_context.Reset ();
  361. this->m_isolate->Dispose ();
  362. }
  363. namespace {
  364. // the line the first stack frame inside `context` points at, with a caret under the column
  365. std::string sourceExcerpt (const std::string& stack, const char* context, const std::string& source) {
  366. const std::string marker = std::string (context) + ":";
  367. const auto at = stack.find (marker);
  368. if (at == std::string::npos) {
  369. return {};
  370. }
  371. int line = 0;
  372. int column = 0;
  373. if (std::sscanf (stack.c_str () + at + marker.size (), "%d:%d", &line, &column) < 1 || line < 1) {
  374. return {};
  375. }
  376. size_t begin = 0;
  377. for (int i = 1; i < line; i++) {
  378. begin = source.find ('\n', begin);
  379. if (begin == std::string::npos) {
  380. return {};
  381. }
  382. begin++;
  383. }
  384. const auto lineEnd = source.find ('\n', begin);
  385. std::string text = source.substr (begin, lineEnd == std::string::npos ? std::string::npos : lineEnd - begin);
  386. std::ranges::replace (text, '\t', ' ');
  387. std::string result = std::to_string (line) + ": " + text;
  388. if (column > 0) {
  389. result += "\n" + std::string (std::to_string (line).size () + 2 + column - 1, ' ') + "^";
  390. }
  391. return result;
  392. }
  393. void logException (
  394. v8::Isolate* isolate, v8::Local<v8::Value> exception, v8::Local<v8::Message> message, const char* context,
  395. const std::optional<std::string>& source
  396. ) {
  397. // scripts that fail every tick would otherwise print the same error every frame
  398. static std::map<std::string, std::string> lastReported;
  399. if (exception.IsEmpty ()) {
  400. sLog.error ("ScriptEngine [", context, "]: script execution was terminated");
  401. return;
  402. }
  403. // toString or a stack getter can throw too
  404. const v8::TryCatch inner (isolate);
  405. const auto jsContext = isolate->GetCurrentContext ();
  406. const std::string text = JS::toString (isolate, exception);
  407. std::string stack;
  408. if (const auto value = JS::get (jsContext, exception, "stack"); value->IsString ()) {
  409. stack = JS::toString (isolate, value);
  410. } else if (!message.IsEmpty ()) {
  411. // a thrown non-Error has no stack, the message still knows where it came from
  412. stack = " at " + JS::toString (isolate, message->GetScriptResourceName ()) + ":"
  413. + std::to_string (message->GetLineNumber (jsContext).FromMaybe (0)) + ":"
  414. + std::to_string (message->GetStartColumn (jsContext).FromMaybe (0) + 1);
  415. }
  416. auto& last = lastReported[context];
  417. if (last == text + stack) {
  418. return;
  419. }
  420. last = text + stack;
  421. sLog.error ("ScriptEngine [", context, "]: ", text);
  422. if (!stack.empty ()) {
  423. sLog.error ("ScriptEngine [", context, "] stack: ", stack);
  424. }
  425. if (source.has_value ()) {
  426. if (const auto excerpt = sourceExcerpt (stack, context, *source); !excerpt.empty ()) {
  427. sLog.error ("ScriptEngine [", context, "] source:\n", excerpt);
  428. }
  429. }
  430. }
  431. } // namespace
  432. void WallpaperEngine::Scripting::logJSException (
  433. v8::Isolate* isolate, const v8::TryCatch& tryCatch, const char* context, const std::optional<std::string>& source
  434. ) {
  435. if (!tryCatch.HasCaught ()) {
  436. sLog.error ("ScriptEngine [", context, "]: a native call failed without setting an exception");
  437. return;
  438. }
  439. logException (isolate, tryCatch.Exception (), tryCatch.Message (), context, source);
  440. }
  441. void ScriptEngine::evaluateGlobalScript (const std::string& source, const char* name) {
  442. const v8::TryCatch tryCatch (this->m_isolate);
  443. const auto context = this->getContext ();
  444. v8::ScriptOrigin origin = JS::origin (this->m_isolate, name, false);
  445. v8::Local<v8::Script> script;
  446. if (!v8::Script::Compile (context, JS::string (this->m_isolate, source), &origin).ToLocal (&script)
  447. || script->Run (context).IsEmpty ()) {
  448. logJSException (this->m_isolate, tryCatch, name, source);
  449. }
  450. }
  451. void ScriptEngine::installBuiltins () { this->evaluateGlobalScript (SCENE_SCRIPT_BUILTINS, "<scene-script-builtins>"); }
  452. void ScriptEngine::ensureLayerRegistry () {
  453. if (this->m_layerRegistryReady) {
  454. return;
  455. }
  456. JS::set (this->getContext (), this->getGlobalThis (), "__textLayers", v8::Object::New (this->m_isolate));
  457. this->m_layerRegistryReady = true;
  458. }
  459. ScriptLayerHandle ScriptEngine::createLayerScript (
  460. const std::string& scriptSource, std::map<std::string, UserSettingUniquePtr>& initialScriptProps,
  461. const std::string& initialText
  462. ) {
  463. const Scope scope (*this);
  464. const auto context = this->getContext ();
  465. const auto global = this->getGlobalThis ();
  466. this->ensureLayerRegistry ();
  467. // Seed initial scriptProperties and text as temporary globals the IIFE reads.
  468. const v8::Local<v8::Object> seedProps = v8::Object::New (this->m_isolate);
  469. for (auto& [name, dynVal] : initialScriptProps) {
  470. JS::set (context, seedProps, name, this->dynamicToJs (*dynVal->value));
  471. }
  472. JS::set (context, global, "__layerSeedProps", seedProps);
  473. JS::set (context, global, "__layerSeedText", JS::string (this->m_isolate, initialText));
  474. const ScriptLayerHandle id = this->m_nextLayerId++;
  475. // WE scripts come as ES6 modules, the text layer sandbox below runs them as a plain script
  476. std::string body = scriptSource;
  477. size_t pos;
  478. while ((pos = body.find ("'use strict';")) != std::string::npos) {
  479. body.erase (pos, 13);
  480. }
  481. while ((pos = body.find ("\"use strict\";")) != std::string::npos) {
  482. body.erase (pos, 13);
  483. }
  484. while ((pos = body.find ("export ")) != std::string::npos) {
  485. body.erase (pos, 7);
  486. }
  487. // The IIFE gives every layer its own closure so two layers both defining `function update()`
  488. // or a top-level `var scriptProperties` don't clobber each other. Lifecycle hooks are
  489. // captured into globalThis.__textLayers[id] so tick/destroy can reach them later.
  490. // `typeof init === 'function'` is safe even when `init` was never declared.
  491. std::ostringstream wrapper;
  492. wrapper
  493. << "(function() {\n"
  494. << " var __id = " << id << ";\n"
  495. << " var __props = Object.assign({}, globalThis.__layerSeedProps || {});\n"
  496. << " var thisLayer = { text: String(globalThis.__layerSeedText || '') };\n"
  497. << " var thisScene = {\n"
  498. << " get time() { var c = globalThis.__sceneCtx; return c ? c.time : 0; },\n"
  499. << " get currentTime() { var c = globalThis.__sceneCtx; return c ? c.time : 0; },\n"
  500. << " get dt() { var c = globalThis.__sceneCtx; return c ? c.dt : 0; },\n"
  501. << " get fps() { var c = globalThis.__sceneCtx; return c ? c.fps : 60; },\n"
  502. << " };\n"
  503. // Minimal WE `engine` shim - just enough for built-in text scripts to run without
  504. // ReferenceError. `frametime` is the per-frame delta in seconds (what InsertFPS reads).
  505. << " var engine = {\n"
  506. << " get frametime() { var c = globalThis.__sceneCtx; return c ? c.dt : 0; },\n"
  507. << " get time() { var c = globalThis.__sceneCtx; return c ? c.time : 0; },\n"
  508. << " };\n"
  509. << " function createScriptProperties() {\n"
  510. << " var builder = {\n"
  511. << " addSlider: function(o){ if (!(o.name in __props)) __props[o.name] = o.value; return builder; },\n"
  512. << " addCheckbox: function(o){ if (!(o.name in __props)) __props[o.name] = o.value; return builder; },\n"
  513. << " addCombo: function(o){ if (!(o.name in __props)) __props[o.name] = o.value; return builder; },\n"
  514. << " addColor: function(o){ if (!(o.name in __props)) __props[o.name] = o.value; return builder; },\n"
  515. << " addText: function(o){ if (!(o.name in __props)) __props[o.name] = o.value; return builder; },\n"
  516. << " finish: function(){ return __props; }\n"
  517. << " };\n"
  518. << " return builder;\n"
  519. << " }\n"
  520. << body
  521. << "\n"
  522. // `_tick` wraps the user's `update()` so both WE text conventions work: mutating
  523. // `thisLayer.text` in place, or returning the new text as a string. Non-string/undefined
  524. // return leaves `thisLayer.text` as whatever the function assigned itself.
  525. << " globalThis.__textLayers[__id] = {\n"
  526. << " thisLayer: thisLayer,\n"
  527. << " thisScene: thisScene,\n"
  528. << " _init: (typeof init === 'function') ? init : null,\n"
  529. << " _destroy: (typeof destroy === 'function') ? destroy : null,\n"
  530. << " _tick: (typeof update === 'function')\n"
  531. << " ? function() {\n"
  532. << " var r = update(thisLayer.text);\n"
  533. << " if (typeof r === 'string') thisLayer.text = r;\n"
  534. << " }\n"
  535. << " : null,\n"
  536. << " _scriptProperties: (typeof scriptProperties !== 'undefined') ? scriptProperties : __props\n"
  537. << " };\n"
  538. << "})();\n";
  539. const v8::TryCatch tryCatch (this->m_isolate);
  540. v8::ScriptOrigin origin = JS::origin (this->m_isolate, "<layer-script>", false);
  541. v8::Local<v8::Script> script;
  542. const bool ok
  543. = v8::Script::Compile (context, JS::string (this->m_isolate, wrapper.str ()), &origin).ToLocal (&script)
  544. && !script->Run (context).IsEmpty ();
  545. if (!ok) {
  546. logJSException (this->m_isolate, tryCatch, "createLayerScript");
  547. }
  548. // Unset seeds so they don't leak into the next createLayerScript call.
  549. JS::set (context, global, "__layerSeedProps", v8::Undefined (this->m_isolate));
  550. JS::set (context, global, "__layerSeedText", v8::Undefined (this->m_isolate));
  551. if (!ok) {
  552. return kInvalidLayerHandle;
  553. }
  554. this->m_layerInitialized[id] = false;
  555. return id;
  556. }
  557. v8::Local<v8::Value> ScriptEngine::textLayer (ScriptLayerHandle handle) {
  558. const auto context = this->getContext ();
  559. const auto layers = JS::get (context, this->getGlobalThis (), "__textLayers");
  560. return JS::get (context, layers, static_cast<uint32_t> (handle));
  561. }
  562. void ScriptEngine::tickLayer (ScriptLayerHandle handle, double time, double deltaTime, double fps) {
  563. if (handle == kInvalidLayerHandle) {
  564. return;
  565. }
  566. const Scope scope (*this);
  567. const auto context = this->getContext ();
  568. const v8::Local<v8::Object> sceneCtx = v8::Object::New (this->m_isolate);
  569. JS::set (context, sceneCtx, "time", v8::Number::New (this->m_isolate, time));
  570. JS::set (context, sceneCtx, "dt", v8::Number::New (this->m_isolate, deltaTime));
  571. JS::set (context, sceneCtx, "fps", v8::Number::New (this->m_isolate, fps));
  572. JS::set (context, this->getGlobalThis (), "__sceneCtx", sceneCtx);
  573. const auto layer = this->textLayer (handle);
  574. if (!layer->IsObject ()) {
  575. return;
  576. }
  577. const auto callHook = [&] (const char* property, const char* tag) {
  578. const v8::TryCatch tryCatch (this->m_isolate);
  579. const auto function = JS::get (context, layer, property);
  580. if (function->IsFunction () && function.As<v8::Function> ()->Call (context, layer, 0, nullptr).IsEmpty ()) {
  581. logJSException (this->m_isolate, tryCatch, tag);
  582. }
  583. };
  584. const auto it = this->m_layerInitialized.find (handle);
  585. if (it != this->m_layerInitialized.end () && !it->second) {
  586. callHook ("_init", "layer.init");
  587. it->second = true;
  588. }
  589. callHook ("_tick", "layer.update");
  590. }
  591. std::string ScriptEngine::layerText (ScriptLayerHandle handle) {
  592. if (handle == kInvalidLayerHandle) {
  593. return {};
  594. }
  595. const Scope scope (*this);
  596. const v8::TryCatch tryCatch (this->m_isolate);
  597. const auto context = this->getContext ();
  598. const auto text = JS::get (context, JS::get (context, this->textLayer (handle), "thisLayer"), "text");
  599. if (text->IsNullOrUndefined ()) {
  600. return {};
  601. }
  602. return JS::toString (this->m_isolate, text);
  603. }
  604. void ScriptEngine::destroyLayer (ScriptLayerHandle handle) {
  605. if (handle == kInvalidLayerHandle) {
  606. return;
  607. }
  608. const Scope scope (*this);
  609. const auto context = this->getContext ();
  610. const auto layer = this->textLayer (handle);
  611. if (layer->IsObject ()) {
  612. const v8::TryCatch tryCatch (this->m_isolate);
  613. const auto function = JS::get (context, layer, "_destroy");
  614. if (function->IsFunction () && function.As<v8::Function> ()->Call (context, layer, 0, nullptr).IsEmpty ()) {
  615. logJSException (this->m_isolate, tryCatch, "layer.destroy");
  616. }
  617. }
  618. // Remove the entry from globalThis.__textLayers so GC can reclaim its closures.
  619. if (const auto layers = JS::get (context, this->getGlobalThis (), "__textLayers"); layers->IsObject ()) {
  620. layers.As<v8::Object> ()->Delete (context, static_cast<uint32_t> (handle)).FromMaybe (false);
  621. }
  622. this->m_layerInitialized.erase (handle);
  623. }
  624. v8::MaybeLocal<v8::Value>
  625. ScriptEngine::call (const LoadedModule& module, const char* name, int argc, v8::Local<v8::Value> argv[]) {
  626. if (module.module.IsEmpty ()) {
  627. return v8::Undefined (this->m_isolate);
  628. }
  629. const auto context = this->getContext ();
  630. const v8::Local<v8::Object> exports = module.module.Get (this->m_isolate);
  631. v8::Local<v8::Value> function;
  632. if (!exports->Get (context, JS::name (this->m_isolate, name)).ToLocal (&function)) {
  633. return {};
  634. }
  635. if (!function->IsFunction ()) {
  636. return v8::Undefined (this->m_isolate);
  637. }
  638. return function.As<v8::Function> ()->Call (context, exports, argc, argv);
  639. }
  640. void ScriptEngine::retireScript (const std::string& key) { this->m_retiredScriptKeys.push_back (key); }
  641. void ScriptEngine::destroyObjectScripts (const ScriptableObject& object) {
  642. {
  643. const Scope scope (*this);
  644. for (auto& module : this->m_scriptModules | std::views::values) {
  645. if (module.object != &object || !module.initialized || module.dropped) {
  646. continue;
  647. }
  648. const v8::TryCatch tryCatch (this->m_isolate);
  649. if (this->callEvent (module, "destroy", 0, nullptr).IsEmpty ()) {
  650. logJSException (this->m_isolate, tryCatch, "destroy", module.value.getScriptSource ());
  651. }
  652. }
  653. }
  654. this->dropObjectScripts (object);
  655. }
  656. void ScriptEngine::dropObjectScripts (const ScriptableObject& object) {
  657. const Scope scope (*this);
  658. const auto context = this->getContext ();
  659. this->m_adapters.object->forget (object);
  660. for (auto& [key, module] : this->m_scriptModules) {
  661. if (module.object != &object) {
  662. continue;
  663. }
  664. module.object = nullptr;
  665. module.dropped = true;
  666. this->retireScript (key);
  667. }
  668. for (const char* global : { "thisLayer", "thisObject" }) {
  669. const auto current = JS::get (context, this->getGlobalThis (), global);
  670. if (this->m_adapters.object->getObject (current) == &object) {
  671. JS::set (context, this->getGlobalThis (), global, v8::Undefined (this->m_isolate));
  672. }
  673. }
  674. }
  675. bool ScriptEngine::rebindScript (const std::string& key, DynamicValue& newValue) {
  676. const auto it = this->m_scriptModules.find (key);
  677. if (it == this->m_scriptModules.end () || it->second.value.getScriptSource () != newValue.getScriptSource ()) {
  678. return false;
  679. }
  680. // LoadedModule::value is a reference member, so the entry is erased and re-emplaced under the same key,
  681. // m_runningModule may currently point at the erased entry
  682. // the cached thisObject points at the old value, the replacement builds its own
  683. LoadedModule replacement { .value = newValue,
  684. .module = std::move (it->second.module),
  685. .object = it->second.object,
  686. .propertyName = it->second.propertyName,
  687. .order = it->second.order,
  688. .key = key };
  689. this->m_scriptModules.erase (it);
  690. const auto inserted = this->m_scriptModules.emplace (key, std::move (replacement));
  691. this->m_runningModule = &inserted.first->second;
  692. return true;
  693. }
  694. void ScriptEngine::queueScript (
  695. const std::string& key, DynamicValue& currentValue, ScriptableObject& object, const std::string& propertyName
  696. ) {
  697. const auto source = currentValue.getScriptSource ();
  698. if (!source.has_value ()) {
  699. return;
  700. }
  701. if (this->m_scriptModules.contains (key)) {
  702. return;
  703. }
  704. const Scope scope (*this);
  705. const auto context = this->getContext ();
  706. const v8::TryCatch tryCatch (this->m_isolate);
  707. // the module's resource name is its key, stack traces and the source excerpt point at it
  708. v8::ScriptCompiler::Source compileSource (
  709. JS::string (this->m_isolate, *source), JS::origin (this->m_isolate, key, true)
  710. );
  711. v8::Local<v8::Module> compiled;
  712. if (!v8::ScriptCompiler::CompileModule (this->m_isolate, &compileSource).ToLocal (&compiled)) {
  713. logJSException (this->m_isolate, tryCatch, key.c_str (), source);
  714. return;
  715. }
  716. // Register the entry and point m_runningModule at it before evaluating below - top-level module code
  717. // commonly does `export var scriptProperties = createScriptProperties()...finish();`, and
  718. // ScriptPropertiesObject's finish() resolves it through getRunningModule(), which must already point here.
  719. auto inserted = this->m_scriptModules.emplace (
  720. key,
  721. LoadedModule {
  722. .value = currentValue,
  723. .object = &object,
  724. .propertyName = propertyName,
  725. .order = this->m_nextModuleOrder++,
  726. .key = key,
  727. }
  728. );
  729. if (!inserted.second) {
  730. return;
  731. }
  732. this->m_runningModule = &inserted.first->second;
  733. // module top-level code (class bodies, helpers instantiated on load) can already touch thisLayer
  734. this->bindThisLayer (object, this->m_runningModule);
  735. const auto fail = [&] (v8::Local<v8::Value> exception) {
  736. if (tryCatch.HasCaught ()) {
  737. logJSException (this->m_isolate, tryCatch, key.c_str (), source);
  738. } else {
  739. logException (this->m_isolate, exception, {}, key.c_str (), source);
  740. }
  741. this->m_runningModule = nullptr;
  742. this->m_scriptModules.erase (key);
  743. };
  744. if (!compiled->InstantiateModule (context, resolveModule).FromMaybe (false)) {
  745. fail ({});
  746. return;
  747. }
  748. // WE evaluates and then checks the module's status (sub_18164BFA0): with top level await V8 returns a promise
  749. // and keeps a throw in the module instead of raising it
  750. const bool wasEvaluatingModuleBody = this->m_evaluatingModuleBody;
  751. this->m_evaluatingModuleBody = true;
  752. const bool evaluated = !compiled->Evaluate (context).IsEmpty ();
  753. this->m_evaluatingModuleBody = wasEvaluatingModuleBody;
  754. // 3378399626's weather widget stores its offsets in shared at the top level from the defaults and only
  755. // picks the user's location up in applyUserProperties
  756. this->m_scriptPropertiesObject->deliverValues (currentValue);
  757. if (!evaluated || compiled->GetStatus () == v8::Module::kErrored) {
  758. fail (compiled->GetStatus () == v8::Module::kErrored ? compiled->GetException () : v8::Local<v8::Value> ());
  759. return;
  760. }
  761. // the entry may have been rebound or dropped while the body ran
  762. const auto entry = this->m_scriptModules.find (key);
  763. if (entry == this->m_scriptModules.end ()) {
  764. return;
  765. }
  766. entry->second.module.Reset (this->m_isolate, compiled->GetModuleNamespace ().As<v8::Object> ());
  767. this->bindThisLayer (object, &entry->second);
  768. // init() and the first update() run from tick(), once the whole scene has been constructed
  769. }
  770. namespace {
  771. // thisObject.getAnimation(): data is [animation system id, the property's DynamicValue]
  772. void this_object_get_animation (const v8::FunctionCallbackInfo<v8::Value>& info) {
  773. auto* isolate = info.GetIsolate ();
  774. const auto context = isolate->GetCurrentContext ();
  775. const int systemId = JS::dataAt (info, 0)->Int32Value (context).FromMaybe (0);
  776. auto* value = JS::unwrap<DynamicValue> (JS::dataAt (info, 1));
  777. auto* system = AnimationSystem::find (systemId);
  778. auto* clock = system == nullptr || value == nullptr ? nullptr : system->clockOf (*value);
  779. if (clock == nullptr) {
  780. info.GetReturnValue ().SetNull ();
  781. return;
  782. }
  783. info.GetReturnValue ().Set (
  784. ScriptEngine::from (isolate).getAdapters ().object->animation (systemId, clock->getId ())
  785. );
  786. }
  787. // thisObject.<property name>: lets a listener registered by a property's script write that property
  788. // from outside (`listener.thisObject['Inner Color'] = color`). data is [the property's DynamicValue, is angles]
  789. void this_object_property (const v8::FunctionCallbackInfo<v8::Value>& info, int magic) {
  790. auto& engine = ScriptEngine::from (info.GetIsolate ());
  791. auto* value = JS::unwrap<DynamicValue> (JS::dataAt (info, 0));
  792. const std::string_view name = JS::dataAt (info, 1)->IsTrue () ? "angles" : "";
  793. if (magic == 0) {
  794. info.GetReturnValue ().Set (engine.propertyToJs (*value, name));
  795. return;
  796. }
  797. if (info.Length () > 0) {
  798. engine.assignPropertyJsValue (info[0], *value, name);
  799. }
  800. }
  801. } // namespace
  802. v8::MaybeLocal<v8::Value> ScriptEngine::findAnimation (const std::string& name, std::optional<int> objectId) {
  803. const auto group = objectId.has_value () ? std::optional ("obj" + std::to_string (*objectId)) : std::nullopt;
  804. auto* clock = this->m_animations.findByName (name, group);
  805. if (clock == nullptr) {
  806. return {};
  807. }
  808. return this->m_adapters.object->animation (this->m_animations.getId (), clock->getId ());
  809. }
  810. v8::MaybeLocal<v8::Value> ScriptEngine::findAnimation (const std::string& name, const std::string& group) {
  811. auto* clock = this->m_animations.findByName (name, group);
  812. if (clock == nullptr) {
  813. return {};
  814. }
  815. return this->m_adapters.object->animation (this->m_animations.getId (), clock->getId ());
  816. }
  817. v8::Local<v8::Value> ScriptEngine::makeThisObject (DynamicValue& value, const std::string& propertyName) {
  818. const auto context = this->getContext ();
  819. const v8::Local<v8::Object> handle = v8::Object::New (this->m_isolate);
  820. JS::set (
  821. context, handle, "getAnimation",
  822. JS::function (
  823. context, this_object_get_animation,
  824. JS::data (
  825. this->m_isolate,
  826. { v8::Integer::New (this->m_isolate, this->m_animations.getId ()),
  827. JS::external (this->m_isolate, &value) }
  828. )
  829. )
  830. );
  831. if (!propertyName.empty ()) {
  832. const auto data = JS::data (
  833. this->m_isolate,
  834. { JS::external (this->m_isolate, &value), v8::Boolean::New (this->m_isolate, propertyName == "angles") }
  835. );
  836. handle->SetAccessorProperty (
  837. JS::name (this->m_isolate, propertyName), JS::function (context, JS::bind<this_object_property, 0>, data),
  838. JS::function (context, JS::bind<this_object_property, 1>, data, 1)
  839. );
  840. }
  841. return handle;
  842. }
  843. void ScriptEngine::bindThisLayer (ScriptableObject& object, LoadedModule* module) {
  844. const auto context = this->getContext ();
  845. const auto global = this->getGlobalThis ();
  846. JS::set (context, global, "thisLayer", this->m_adapters.object->instantiate (object));
  847. // thisObject is the property the running script is attached to (what getAnimation() hangs
  848. // off), not the layer
  849. if (module == nullptr) {
  850. JS::set (context, global, "thisObject", this->m_adapters.object->instantiate (object));
  851. return;
  852. }
  853. if (module->thisObject.IsEmpty ()) {
  854. module->thisObject.Reset (
  855. this->m_isolate,
  856. module->thisObjectFactory ? module->thisObjectFactory (*this)
  857. : this->makeThisObject (module->value, module->propertyName)
  858. );
  859. }
  860. JS::set (context, global, "thisObject", module->thisObject.Get (this->m_isolate));
  861. }
  862. void ScriptEngine::dispatchAnimationEvents () {
  863. const auto context = this->getContext ();
  864. for (const auto& event : this->m_animations.takeEvents ()) {
  865. const auto* clock = this->m_animations.clock (event.clock);
  866. if (clock == nullptr) {
  867. continue;
  868. }
  869. for (auto& [key, module] : this->m_scriptModules) {
  870. if (&module.value != &clock->getRootValue () || !module.initialized || module.dropped) {
  871. continue;
  872. }
  873. const v8::HandleScope handleScope (this->m_isolate);
  874. const v8::TryCatch tryCatch (this->m_isolate);
  875. this->m_runningModule = &module;
  876. if (module.object != nullptr) {
  877. this->bindThisLayer (*module.object, &module);
  878. }
  879. const v8::Local<v8::Object> eventObject = v8::Object::New (this->m_isolate);
  880. JS::set (context, eventObject, "name", JS::string (this->m_isolate, event.name));
  881. JS::set (context, eventObject, "frame", v8::Number::New (this->m_isolate, event.frame));
  882. v8::Local<v8::Value> args[] = { eventObject, this->propertyToJs (module.value, module.propertyName) };
  883. v8::Local<v8::Value> result;
  884. if (!this->call (module, "animationEvent", 2, args).ToLocal (&result)) {
  885. logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
  886. } else {
  887. // like update(), the handler's return value becomes the property's new value
  888. this->assignPropertyJsValue (result, module.value, module.propertyName);
  889. }
  890. break;
  891. }
  892. }
  893. }
  894. void ScriptEngine::initializeModule (const std::string& key, LoadedModule& module) {
  895. const auto context = this->getContext ();
  896. module.initialized = true;
  897. // init() receives the property's static/base value exactly once, before update() starts being
  898. // called every tick - scripts commonly stash it (e.g. audio-reactive scale scripts scaling a
  899. // captured base value) and would otherwise read undefined forever.
  900. {
  901. const v8::TryCatch tryCatch (this->m_isolate);
  902. v8::Local<v8::Value> initArgs[] = { this->propertyToJs (module.value, module.propertyName) };
  903. const DynamicValue valueBeforeInit (module.value);
  904. v8::Local<v8::Value> initResult;
  905. if (!this->call (module, "init", 1, initArgs).ToLocal (&initResult)) {
  906. logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
  907. } else if (
  908. valueBeforeInit.getType () == module.value.getType ()
  909. && valueBeforeInit.getVec4 () == module.value.getVec4 ()
  910. && valueBeforeInit.getString () == module.value.getString ()
  911. ) {
  912. // init() may hand back a different starting value, unless something already moved the property meanwhile
  913. this->assignPropertyJsValue (initResult, module.value, module.propertyName);
  914. }
  915. }
  916. // the real engine hands every user property to applyUserProperties() once at load (and only the
  917. // changed ones afterward) - scripts like music selectors rely on that first call to start up
  918. {
  919. const v8::TryCatch tryCatch (this->m_isolate);
  920. const v8::Local<v8::Object> userProps = v8::Object::New (this->m_isolate);
  921. for (const auto& [name, property] : this->m_engineObject->getScene ().getUserProperties ()) {
  922. JS::set (context, userProps, name, this->userPropertyToJs (*property));
  923. }
  924. v8::Local<v8::Value> applyArgs[] = { userProps };
  925. if (this->call (module, "applyUserProperties", 1, applyArgs).IsEmpty ()) {
  926. logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
  927. }
  928. }
  929. this->notifyMediaUpdate (this->m_mediaSource.getMediaInfo (), &module);
  930. }
  931. namespace {
  932. constexpr const char* CURSOR_HANDLERS[]
  933. = { "cursorEnter", "cursorLeave", "cursorMove", "cursorDown", "cursorUp", "cursorClick" };
  934. }
  935. bool ScriptEngine::hasCursorHandlers (const ScriptableObject& object) {
  936. const Scope scope (*this);
  937. const auto context = this->getContext ();
  938. for (auto& module : this->m_scriptModules | std::views::values) {
  939. if (module.object != &object || !module.initialized || module.module.IsEmpty ()) {
  940. continue;
  941. }
  942. if (module.cursorHandlers < 0) {
  943. const v8::TryCatch tryCatch (this->m_isolate);
  944. module.cursorHandlers = 0;
  945. for (const char* handler : CURSOR_HANDLERS) {
  946. if (JS::get (context, module.module.Get (this->m_isolate), handler)->IsFunction ()) {
  947. module.cursorHandlers = 1;
  948. }
  949. }
  950. }
  951. if (module.cursorHandlers > 0) {
  952. return true;
  953. }
  954. }
  955. return false;
  956. }
  957. void ScriptEngine::dispatchCursorEvent (
  958. const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition,
  959. const std::optional<std::string>& hitBox
  960. ) {
  961. const Scope scope (*this);
  962. const auto context = this->getContext ();
  963. // Vec3 per WE's lib.sceneScript.d.ts, scripts call add()/subtract() on them
  964. const auto makePosition = [this] (const glm::vec3& value) {
  965. DynamicValue position (value);
  966. return this->m_adapters.vec3->instantiate (position);
  967. };
  968. for (auto& [key, module] : this->m_scriptModules) {
  969. if (module.object != &object || !module.initialized || module.cursorHandlers <= 0) {
  970. continue;
  971. }
  972. const v8::HandleScope handleScope (this->m_isolate);
  973. const v8::TryCatch tryCatch (this->m_isolate);
  974. this->m_runningModule = &module;
  975. this->bindThisLayer (*module.object, &module);
  976. const v8::Local<v8::Object> event = v8::Object::New (this->m_isolate);
  977. JS::set (context, event, "button", v8::Integer::New (this->m_isolate, 0));
  978. JS::set (context, event, "worldPosition", makePosition (glm::vec3 (worldPosition, 0.0f)));
  979. JS::set (context, event, "localPosition", makePosition (localPosition));
  980. if (hitBox.has_value ()) {
  981. JS::set (context, event, "hitBox", JS::string (this->m_isolate, *hitBox));
  982. }
  983. v8::Local<v8::Value> args[] = { event };
  984. if (this->call (module, handler, 1, args).IsEmpty ()) {
  985. logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
  986. }
  987. }
  988. this->m_runningModule = nullptr;
  989. }
  990. void ScriptEngine::addVideoEndedCallback (VideoPlayback::MPV::GLPlayer* player, v8::Local<v8::Value> callback) {
  991. if (player == nullptr || !callback->IsFunction ()) {
  992. return;
  993. }
  994. this->m_videoEndedCallbacks.push_back (
  995. { .player = player, .callback = v8::Global<v8::Function> (this->m_isolate, callback.As<v8::Function> ()) }
  996. );
  997. }
  998. void ScriptEngine::addAnimationLayerEndedCallback (
  999. const ScriptableObject& owner, size_t serial, v8::Local<v8::Value> callback
  1000. ) {
  1001. if (!callback->IsFunction ()) {
  1002. return;
  1003. }
  1004. this->m_animationLayerEndedCallbacks.push_back (
  1005. { .owner = &owner,
  1006. .serial = serial,
  1007. .callback = v8::Global<v8::Function> (this->m_isolate, callback.As<v8::Function> ()),
  1008. .module = this->m_runningModule }
  1009. );
  1010. }
  1011. void ScriptEngine::dispatchAnimationLayerEnded (const ScriptableObject& owner, size_t serial) {
  1012. const Scope scope (*this);
  1013. const auto context = this->getContext ();
  1014. // index based, a callback is free to register more callbacks
  1015. for (size_t index = 0; index < this->m_animationLayerEndedCallbacks.size (); index++) {
  1016. const auto& entry = this->m_animationLayerEndedCallbacks[index];
  1017. if (entry.owner != &owner || entry.serial != serial) {
  1018. continue;
  1019. }
  1020. // the registering module may have been retired since, only a live one gets rebound
  1021. LoadedModule* module = nullptr;
  1022. for (auto& candidate : this->m_scriptModules | std::views::values) {
  1023. if (&candidate == entry.module && !candidate.dropped && candidate.object != nullptr) {
  1024. module = &candidate;
  1025. break;
  1026. }
  1027. }
  1028. const v8::HandleScope handleScope (this->m_isolate);
  1029. const v8::TryCatch tryCatch (this->m_isolate);
  1030. const v8::Local<v8::Function> callback = entry.callback.Get (this->m_isolate);
  1031. LoadedModule* previous = this->m_runningModule;
  1032. if (module != nullptr) {
  1033. this->m_runningModule = module;
  1034. this->bindThisLayer (*module->object, module);
  1035. }
  1036. if (callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ()) {
  1037. logJSException (this->m_isolate, tryCatch, "animation layer ended callback");
  1038. }
  1039. this->m_runningModule = previous;
  1040. }
  1041. }
  1042. void ScriptEngine::dispatchClipEvent (const ScriptableObject& owner, const std::string& payload) {
  1043. const Scope scope (*this);
  1044. const auto context = this->getContext ();
  1045. for (auto& [key, module] : this->m_scriptModules) {
  1046. if (module.object != &owner || !module.initialized || module.dropped || module.module.IsEmpty ()) {
  1047. continue;
  1048. }
  1049. const v8::HandleScope handleScope (this->m_isolate);
  1050. v8::Local<v8::Value> function;
  1051. if (!module.module.Get (this->m_isolate)
  1052. ->Get (context, JS::name (this->m_isolate, "animationEvent"))
  1053. .ToLocal (&function)
  1054. || !function->IsFunction ()) {
  1055. continue;
  1056. }
  1057. v8::Local<v8::Value> event = v8::Null (this->m_isolate);
  1058. {
  1059. const v8::TryCatch parseCatch (this->m_isolate);
  1060. v8::Local<v8::Value> parsed;
  1061. if (v8::JSON::Parse (context, JS::string (this->m_isolate, payload)).ToLocal (&parsed)) {
  1062. event = parsed;
  1063. }
  1064. }
  1065. const v8::TryCatch tryCatch (this->m_isolate);
  1066. LoadedModule* previous = this->m_runningModule;
  1067. this->m_runningModule = &module;
  1068. this->bindThisLayer (*module.object, &module);
  1069. v8::Local<v8::Value> args[] = { event, this->propertyToJs (module.value, module.propertyName) };
  1070. v8::Local<v8::Value> result;
  1071. if (!this->call (module, "animationEvent", 2, args).ToLocal (&result)) {
  1072. logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
  1073. } else {
  1074. this->assignPropertyJsValue (result, module.value, module.propertyName);
  1075. }
  1076. this->m_runningModule = previous;
  1077. }
  1078. }
  1079. v8::MaybeLocal<v8::Value> ScriptEngine::callAsModule (const std::string& key, v8::Local<v8::Function> callback) {
  1080. const auto it = this->m_scriptModules.find (key);
  1081. LoadedModule* module = it == this->m_scriptModules.end () || it->second.dropped ? nullptr : &it->second;
  1082. LoadedModule* previous = this->m_runningModule;
  1083. if (module != nullptr) {
  1084. this->m_runningModule = module;
  1085. if (module->object != nullptr) {
  1086. this->bindThisLayer (*module->object, module);
  1087. }
  1088. }
  1089. const auto result = callback->Call (this->getContext (), v8::Undefined (this->m_isolate), 0, nullptr);
  1090. this->m_runningModule = previous;
  1091. return result;
  1092. }
  1093. void ScriptEngine::setThisObjectFactory (
  1094. const std::string& key, std::function<v8::Local<v8::Value> (ScriptEngine&)> factory
  1095. ) {
  1096. const auto it = this->m_scriptModules.find (key);
  1097. if (it == this->m_scriptModules.end ()) {
  1098. return;
  1099. }
  1100. it->second.thisObjectFactory = std::move (factory);
  1101. it->second.thisObject.Reset ();
  1102. }
  1103. void ScriptEngine::initializePending () {
  1104. const Scope scope (*this);
  1105. LoadedModule* previous = this->m_runningModule;
  1106. // init () can create layers with scripts of their own
  1107. for (bool again = true; again;) {
  1108. again = false;
  1109. std::vector<std::pair<uint64_t, std::string>> order;
  1110. for (const auto& [key, module] : this->m_scriptModules) {
  1111. if (!module.initialized && !module.dropped) {
  1112. order.emplace_back (module.order, key);
  1113. }
  1114. }
  1115. std::ranges::sort (order);
  1116. for (const auto& [unused, key] : order) {
  1117. const auto entry = this->m_scriptModules.find (key);
  1118. if (entry == this->m_scriptModules.end () || entry->second.dropped || entry->second.initialized) {
  1119. continue;
  1120. }
  1121. auto& module = entry->second;
  1122. const v8::HandleScope handleScope (this->m_isolate);
  1123. this->m_runningModule = &module;
  1124. if (module.object != nullptr) {
  1125. this->bindThisLayer (*module.object, &module);
  1126. }
  1127. this->initializeModule (key, module);
  1128. again = true;
  1129. }
  1130. }
  1131. this->m_runningModule = previous;
  1132. }
  1133. void ScriptEngine::tick () {
  1134. const Scope scope (*this);
  1135. const auto context = this->getContext ();
  1136. // tasks V8 posts back to this thread (GC finalization, compile jobs) only run when asked to
  1137. while (v8::platform::PumpMessageLoop (&JS::platform (), this->m_isolate)) { }
  1138. this->m_engineObject->tick ();
  1139. // index based, a callback is free to register more callbacks (and reallocate the vector)
  1140. for (size_t index = 0; index < this->m_videoEndedCallbacks.size (); index++) {
  1141. auto& entry = this->m_videoEndedCallbacks[index];
  1142. if (!entry.player->hasEnded ()) {
  1143. entry.notified = false;
  1144. continue;
  1145. }
  1146. if (entry.notified) {
  1147. continue;
  1148. }
  1149. entry.notified = true;
  1150. const v8::HandleScope handleScope (this->m_isolate);
  1151. const v8::TryCatch tryCatch (this->m_isolate);
  1152. const v8::Local<v8::Function> callback = entry.callback.Get (this->m_isolate);
  1153. if (callback->Call (context, v8::Undefined (this->m_isolate), 0, nullptr).IsEmpty ()) {
  1154. logJSException (this->m_isolate, tryCatch, "video ended callback");
  1155. }
  1156. }
  1157. // safe to erase retired modules now, nothing is mid-iteration and no queueScript() is on the stack
  1158. for (const auto& key : this->m_retiredScriptKeys) {
  1159. this->m_scriptModules.erase (key);
  1160. }
  1161. this->m_retiredScriptKeys.clear ();
  1162. // long stalls (window dragged, suspend) shouldn't skip whole animations
  1163. this->m_animations.tick (std::clamp (g_Time - g_TimeLast, 0.0f, 0.25f));
  1164. // scene order like WE, not the order of the keys: 3444535389's bee script reads shared values that the
  1165. // setup script of an earlier object writes, run before it the bee's position turned NaN for good.
  1166. // Keys are looked up again per module, an update() may rebind (erase and re-add) an entry.
  1167. std::vector<std::pair<uint64_t, std::string>> order;
  1168. order.reserve (this->m_scriptModules.size ());
  1169. for (const auto& [key, module] : this->m_scriptModules) {
  1170. order.emplace_back (module.order, key);
  1171. }
  1172. std::ranges::sort (order);
  1173. for (const auto& [unused, key] : order) {
  1174. const auto entry = this->m_scriptModules.find (key);
  1175. if (entry == this->m_scriptModules.end () || entry->second.dropped) {
  1176. continue;
  1177. }
  1178. auto& module = entry->second;
  1179. const v8::HandleScope handleScope (this->m_isolate);
  1180. this->m_runningModule = &module;
  1181. // `thisLayer` is a single global binding shared by every module and only set once, at
  1182. // registration in queueScript() - without rebinding it here, every module but the last
  1183. // registered would see whatever object queueScript() last ran for, not its own layer.
  1184. if (module.object != nullptr) {
  1185. this->bindThisLayer (*module.object, &module);
  1186. }
  1187. if (!module.initialized) {
  1188. this->initializeModule (key, module);
  1189. }
  1190. const v8::TryCatch tryCatch (this->m_isolate);
  1191. v8::Local<v8::Value> args[] = { this->propertyToJs (module.value, module.propertyName) };
  1192. v8::Local<v8::Value> result;
  1193. // scenescript64 keeps the index of the export being called (+1580, 1 = update) for IModelData.replaceData
  1194. this->m_runningUpdate = true;
  1195. const bool ok = this->call (module, "update", 1, args).ToLocal (&result);
  1196. this->m_runningUpdate = false;
  1197. if (!ok) {
  1198. logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
  1199. continue;
  1200. }
  1201. if (key.starts_with ("scale_")) {
  1202. static int scaleDiagnosticCounter = 0;
  1203. if (++scaleDiagnosticCounter >= 300) {
  1204. scaleDiagnosticCounter = 0;
  1205. sLog.debug (
  1206. "scale script '", key, "': update() returned ",
  1207. JS::toString (this->m_isolate, result->TypeOf (this->m_isolate)), ", current vec3 = (",
  1208. module.value.getVec3 ().x, ", ", module.value.getVec3 ().y, ", ", module.value.getVec3 ().z, ")"
  1209. );
  1210. }
  1211. // Edge-triggered marker for when a pulse lands visually, timestamped so it can be
  1212. // correlated against when the sound was played.
  1213. static std::map<std::string, bool> wasPulsing;
  1214. const bool pulsingNow = std::abs (module.value.getVec3 ().x - 1.0f) > 0.03f;
  1215. if (pulsingNow && !wasPulsing[key]) {
  1216. const auto now = std::chrono::system_clock::now ();
  1217. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds> (now.time_since_epoch ()) % 1000;
  1218. const std::time_t t = std::chrono::system_clock::to_time_t (now);
  1219. std::tm tmBuf {};
  1220. localtime_r (&t, &tmBuf);
  1221. char buf[16];
  1222. std::strftime (buf, sizeof (buf), "%H:%M:%S", &tmBuf);
  1223. sLog.debug (
  1224. "[", buf, ".", (ms.count () < 100 ? "0" : ""), (ms.count () < 10 ? "0" : ""), ms.count (),
  1225. "] scale script '", key, "': PULSE, vec3.x=", module.value.getVec3 ().x
  1226. );
  1227. }
  1228. wasPulsing[key] = pulsingNow;
  1229. }
  1230. this->assignPropertyJsValue (result, module.value, module.propertyName);
  1231. }
  1232. this->dispatchAnimationEvents ();
  1233. }
  1234. Media::ThumbnailPalette ScriptEngine::thumbnailPaletteFor (const Media::MediaSource::MediaInfo& media) {
  1235. if (!media.url.has_value ()) {
  1236. return {};
  1237. }
  1238. // every module gets the event, decode the cover once per file
  1239. if (this->m_paletteUrl == *media.url) {
  1240. return this->m_palette;
  1241. }
  1242. this->m_paletteUrl = *media.url;
  1243. this->m_palette = {};
  1244. std::string path = *media.url;
  1245. if (!path.starts_with ("file://")) {
  1246. return this->m_palette;
  1247. }
  1248. this->m_palette = Media::loadThumbnailPalette (path.substr (7));
  1249. return this->m_palette;
  1250. }
  1251. v8::MaybeLocal<v8::Value>
  1252. ScriptEngine::callEvent (LoadedModule& module, const char* name, int argc, v8::Local<v8::Value> argv[]) {
  1253. // with its own layer as thisLayer
  1254. LoadedModule* previous = this->m_runningModule;
  1255. this->m_runningModule = &module;
  1256. if (module.object != nullptr) {
  1257. this->bindThisLayer (*module.object, &module);
  1258. }
  1259. const auto result = this->call (module, name, argc, argv);
  1260. this->m_runningModule = previous;
  1261. return result;
  1262. }
  1263. void ScriptEngine::notifyResizeScreen (const glm::vec2& size) {
  1264. const Scope scope (*this);
  1265. auto* isolate = this->m_isolate;
  1266. for (auto& module : this->m_scriptModules | std::views::values) {
  1267. if (!module.initialized || module.dropped) {
  1268. continue;
  1269. }
  1270. const v8::TryCatch tryCatch (isolate);
  1271. v8::Local<v8::Value> args[] = { this->m_adapters.vec2->create (size) };
  1272. if (this->callEvent (module, "resizeScreen", 1, args).IsEmpty ()) {
  1273. logJSException (isolate, tryCatch, "resizeScreen", module.value.getScriptSource ());
  1274. }
  1275. }
  1276. }
  1277. void ScriptEngine::notifyUserPropertiesChanged (const std::vector<std::string>& names) {
  1278. const Scope scope (*this);
  1279. this->m_scriptPropertiesObject->userPropertiesChanged (names);
  1280. const auto context = this->getContext ();
  1281. auto* isolate = this->m_isolate;
  1282. const auto& properties = this->m_engineObject->getScene ().getUserProperties ();
  1283. for (auto& module : this->m_scriptModules | std::views::values) {
  1284. if (!module.initialized || module.dropped) {
  1285. continue;
  1286. }
  1287. const v8::TryCatch tryCatch (isolate);
  1288. const v8::Local<v8::Object> userProps = v8::Object::New (isolate);
  1289. for (const auto& name : names) {
  1290. if (const auto it = properties.find (name); it != properties.end ()) {
  1291. JS::set (context, userProps, name, this->userPropertyToJs (*it->second));
  1292. }
  1293. }
  1294. v8::Local<v8::Value> args[] = { userProps };
  1295. if (this->callEvent (module, "applyUserProperties", 1, args).IsEmpty ()) {
  1296. logJSException (isolate, tryCatch, "applyUserProperties", module.value.getScriptSource ());
  1297. }
  1298. }
  1299. }
  1300. void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, LoadedModule* only) {
  1301. const Scope scope (*this);
  1302. const auto context = this->getContext ();
  1303. auto* isolate = this->m_isolate;
  1304. const auto palette = this->thumbnailPaletteFor (media);
  1305. const auto color = [this] (const glm::vec3& value) {
  1306. DynamicValue dynamic (value);
  1307. return this->m_adapters.vec3->instantiate (dynamic);
  1308. };
  1309. // sub_18164E4D0 cases 14 to 18
  1310. const v8::Local<v8::Object> statusEvent = v8::Object::New (isolate);
  1311. JS::set (context, statusEvent, "enabled", v8::Boolean::New (isolate, true));
  1312. const v8::Local<v8::Object> propertiesEvent = v8::Object::New (isolate);
  1313. // SMTC subtitle and content type have no MPRIS counterpart
  1314. JS::set (context, propertiesEvent, "title", JS::string (isolate, media.title));
  1315. JS::set (context, propertiesEvent, "artist", JS::string (isolate, media.artist));
  1316. JS::set (context, propertiesEvent, "albumArtist", JS::string (isolate, media.albumArtist));
  1317. JS::set (context, propertiesEvent, "albumTitle", JS::string (isolate, media.album));
  1318. JS::set (context, propertiesEvent, "subTitle", JS::string (isolate, ""));
  1319. JS::set (context, propertiesEvent, "genres", JS::string (isolate, media.genres));
  1320. JS::set (context, propertiesEvent, "contentType", JS::string (isolate, ""));
  1321. const v8::Local<v8::Object> playbackEvent = v8::Object::New (isolate);
  1322. JS::set (context, playbackEvent, "state", v8::Integer::New (isolate, media.playbackState));
  1323. const v8::Local<v8::Object> mediaTimelineEvent = v8::Object::New (isolate);
  1324. JS::set (context, mediaTimelineEvent, "position", v8::Number::New (isolate, media.position));
  1325. JS::set (context, mediaTimelineEvent, "duration", v8::Number::New (isolate, media.duration));
  1326. const v8::Local<v8::Object> mediaThumbnailEvent = v8::Object::New (isolate);
  1327. JS::set (context, mediaThumbnailEvent, "hasThumbnail", v8::Boolean::New (isolate, media.url.has_value ()));
  1328. JS::set (context, mediaThumbnailEvent, "primaryColor", color (palette.primary));
  1329. JS::set (context, mediaThumbnailEvent, "secondaryColor", color (palette.secondary));
  1330. JS::set (context, mediaThumbnailEvent, "tertiaryColor", color (palette.tertiary));
  1331. JS::set (context, mediaThumbnailEvent, "textColor", color (palette.text));
  1332. JS::set (context, mediaThumbnailEvent, "highContrastColor", color (palette.highContrast));
  1333. std::vector<std::pair<const char*, v8::Local<v8::Value>>> events;
  1334. if (only != nullptr) {
  1335. // on load (sub_140172830): status, then playback state, properties, thumbnail and timeline
  1336. events.emplace_back ("mediaStatusChanged", statusEvent);
  1337. if (media.available && media.playbackState != Media::MediaSource::Stopped) {
  1338. events.emplace_back ("mediaPlaybackChanged", playbackEvent);
  1339. }
  1340. if (media.available && !media.title.empty ()) {
  1341. events.emplace_back ("mediaPropertiesChanged", propertiesEvent);
  1342. }
  1343. if (media.available && media.url.has_value ()) {
  1344. events.emplace_back ("mediaThumbnailChanged", mediaThumbnailEvent);
  1345. }
  1346. if (media.available && media.duration != 0.0) {
  1347. events.emplace_back ("mediaTimelineChanged", mediaTimelineEvent);
  1348. }
  1349. } else {
  1350. events = {
  1351. { "mediaPropertiesChanged", propertiesEvent },
  1352. { "mediaPlaybackChanged", playbackEvent },
  1353. { "mediaTimelineChanged", mediaTimelineEvent },
  1354. { "mediaThumbnailChanged", mediaThumbnailEvent },
  1355. };
  1356. }
  1357. for (auto& module : this->m_scriptModules | std::views::values) {
  1358. // modules that haven't run init() yet get the current media state replayed once they do
  1359. if (!module.initialized || (only != nullptr && only != &module)) {
  1360. continue;
  1361. }
  1362. for (auto [handler, event] : events) {
  1363. const v8::TryCatch tryCatch (isolate);
  1364. v8::Local<v8::Value> args[] = { event };
  1365. if (this->callEvent (module, handler, 1, args).IsEmpty ()) {
  1366. logJSException (isolate, tryCatch, handler, module.value.getScriptSource ());
  1367. }
  1368. }
  1369. }
  1370. }