js_browser.c 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393
  1. /* Browser bindings for the page JavaScript engine (QuickJS, driven through
  2. * the MuJS-style stack API in js_mu.c): the DOM layer (interned node wrappers,
  3. * attributes, query selectors, classList/dataset/style, innerHTML, timers)
  4. * plus document/window/location/navigator globals. */
  5. #include <setjmp.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "ucmd_lib.h"
  11. #include "browser_html.h"
  12. #include "js_browser.h"
  13. #include "js_mu.h"
  14. /* Wall-clock budget per script/handler/timer entry, in milliseconds. It is
  15. * reset before every entry; a runaway loop becomes a catchable
  16. * "interrupted" exception instead of a frozen browser. A framework
  17. * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a
  18. * slow CPU, so the budget is generous. */
  19. #define JS_RUN_LIMIT 20000
  20. #define JS_TIMERS 64
  21. struct js_timer {
  22. int used;
  23. int repeat;
  24. unsigned int deadline;
  25. unsigned int interval;
  26. char ref[32];
  27. };
  28. static struct js_timer timers[JS_TIMERS];
  29. static js_State *J;
  30. static struct br_doc *D;
  31. static struct js_browser_host host;
  32. static const char *current_url;
  33. static jmp_buf panic_env;
  34. static int panic_armed;
  35. static void report_top(js_State *state);
  36. static void report_cb(js_State *state, const char *message)
  37. {
  38. (void)state;
  39. if (host.report)
  40. host.report(message);
  41. }
  42. static void panic_cb(js_State *state)
  43. {
  44. if (panic_armed)
  45. longjmp(panic_env, 1);
  46. if (js_isobject(state, -1))
  47. report_top(state);
  48. else if (host.report)
  49. host.report(js_trystring(state, -1,
  50. "uncaught JavaScript exception"));
  51. if (host.report)
  52. host.report("uncaught JavaScript exception");
  53. }
  54. static unsigned int node_of(void *p)
  55. {
  56. return (unsigned int)(uintptr_t)p - 1;
  57. }
  58. static int node_has(js_State *state, void *p, const char *name);
  59. static int node_put(js_State *state, void *p, const char *name);
  60. static int node_delete(js_State *state, void *p, const char *name);
  61. static void push_element_url(js_State *state, unsigned int node,
  62. const char *name);
  63. static void rellist_supports(js_State *state);
  64. static void push_query_array(js_State *state, unsigned int root,
  65. const char *selector);
  66. static void node_push_text(js_State *state, unsigned int node);
  67. static void url_resolve(const char *base, const char *rel,
  68. char *out, unsigned int cap);
  69. static int hash_pending;
  70. /* One wrapper per DOM node: the same element must have the same object
  71. * identity on every access, or library caches (jQuery expando data, Sizzle)
  72. * silently split into disconnected copies. */
  73. static void push_node(js_State *state, unsigned int handle)
  74. {
  75. char key[24];
  76. if (!handle) {
  77. js_pushnull(state);
  78. return;
  79. }
  80. snprintf(key, sizeof(key), "jsonnode_%u", handle);
  81. js_getregistry(state, key);
  82. if (!js_isundefined(state, -1))
  83. return;
  84. js_pop(state, 1);
  85. /* js_newuserdatax() pops a prototype from the top. Wrappers inherit
  86. * from Object.prototype like real DOM nodes (toString/hasOwnProperty;
  87. * Angular calls node.toString() to sniff SVG). */
  88. js_getregistry(state, "nodeproto");
  89. js_newuserdatax(state, "node", (void *)(uintptr_t)handle,
  90. node_has, node_put, node_delete, 0);
  91. js_copy(state, -1);
  92. js_setregistry(state, key);
  93. }
  94. static unsigned int arg_node(js_State *state, int idx)
  95. {
  96. if (!js_isuserdata(state, idx, "node"))
  97. js_typeerror(state, "not a DOM node");
  98. return (unsigned int)(uintptr_t)js_touserdata(state, idx, "node");
  99. }
  100. static void def_func_data(js_State *state, const char *name,
  101. js_CFunction fn, int length, unsigned int handle)
  102. {
  103. js_newcfunctionx(state, fn, name, length,
  104. (void *)(uintptr_t)handle, 0);
  105. js_setproperty(state, -2, name);
  106. }
  107. static void def_func(js_State *state, const char *name,
  108. js_CFunction fn, int length)
  109. {
  110. js_newcfunction(state, fn, name, length);
  111. js_setproperty(state, -2, name);
  112. }
  113. static void def_global_func(js_State *state, const char *name,
  114. js_CFunction fn, int length)
  115. {
  116. js_newcfunction(state, fn, name, length);
  117. js_defglobal(state, name, JS_DONTENUM);
  118. }
  119. static void push_func_data(js_State *state, const char *name,
  120. js_CFunction fn, int length, unsigned int handle)
  121. {
  122. js_newcfunctionx(state, fn, name, length,
  123. (void *)(uintptr_t)handle, 0);
  124. }
  125. static const char *node_attr(unsigned int node, const char *name)
  126. {
  127. return br_find_attr(D, node, name);
  128. }
  129. static void push_attr(js_State *state, unsigned int node, const char *name,
  130. int null_if_missing)
  131. {
  132. const char *s = node_attr(node, name);
  133. if (s)
  134. js_pushstring(state, s);
  135. else if (null_if_missing)
  136. js_pushnull(state);
  137. else
  138. js_pushstring(state, "");
  139. }
  140. static unsigned int node_name(unsigned int node, char *buf, unsigned int cap)
  141. {
  142. struct br_node *n;
  143. const char *s;
  144. unsigned int i = 0;
  145. if (!D || node >= D->nnode || cap == 0)
  146. return 0;
  147. n = &D->nodes[node];
  148. if (n->type == BR_NODE_TEXT)
  149. s = "#text";
  150. else if (n->type == BR_NODE_COMMENT)
  151. s = "#comment";
  152. else if (n->type == BR_NODE_FRAGMENT)
  153. s = "#document-fragment";
  154. else if (n->tag == BR_TAG_UNKNOWN && n->name_off)
  155. s = D->attrs + n->name_off;
  156. else
  157. s = br_tag_name(n->tag);
  158. while (s && *s && i + 1 < cap) {
  159. char c = *s++;
  160. if (c >= 'a' && c <= 'z')
  161. c = (char)(c - 'a' + 'A');
  162. buf[i++] = c;
  163. }
  164. buf[i] = '\0';
  165. return i;
  166. }
  167. /* ---- DOM events ------------------------------------------------------- *
  168. *
  169. * Listeners live in a fixed table, one entry per (target, type, callback)
  170. * registration, and callbacks are retained through the engine registry. The
  171. * dispatcher walks the parent chain for bubbling and runs one listener at a
  172. * time so a handler can safely mutate the tree. `preventDefault` is tracked
  173. * per dispatch in a small event-state table and mirrored onto the event
  174. * object, so a submit handler can cancel the browser's default action. */
  175. #define JS_LISTENERS 256
  176. #define JS_EVENT_SLOTS 8
  177. #define JS_EVENT_TEMPLATES 16
  178. #define JS_TARGET_WINDOW 0xFFFFFFF0u
  179. #define JS_TARGET_DOCUMENT 0xFFFFFFF1u
  180. struct js_listener {
  181. unsigned char used;
  182. unsigned char capture;
  183. unsigned int target;
  184. char type[24];
  185. char ref[32];
  186. };
  187. struct js_event_state {
  188. int used;
  189. int prevented;
  190. int stopped;
  191. int immediate;
  192. char objref[32];
  193. };
  194. struct js_template {
  195. int used;
  196. char ref[32];
  197. };
  198. static struct js_listener listeners[JS_LISTENERS];
  199. static struct js_event_state events[JS_EVENT_SLOTS];
  200. static struct js_template event_templates[JS_EVENT_TEMPLATES];
  201. static void push_event_target(js_State *state, unsigned int target)
  202. {
  203. if (target == JS_TARGET_WINDOW)
  204. js_pushglobal(state);
  205. else if (target == JS_TARGET_DOCUMENT)
  206. js_getglobal(state, "document");
  207. else
  208. push_node(state, target + 1);
  209. }
  210. static void obj_set(js_State *state, int idx, const char *name)
  211. {
  212. /* The value was just pushed, so a negative object index moved down. */
  213. if (idx < 0)
  214. idx--;
  215. js_setproperty(state, idx, name);
  216. }
  217. static void obj_set_string(js_State *state, int idx, const char *name,
  218. const char *value)
  219. {
  220. js_pushstring(state, value ? value : "");
  221. obj_set(state, idx, name);
  222. }
  223. static void obj_set_bool(js_State *state, int idx, const char *name, int value)
  224. {
  225. js_pushboolean(state, value != 0);
  226. obj_set(state, idx, name);
  227. }
  228. static int event_slot(js_State *state)
  229. {
  230. int slot = (int)(uintptr_t)js_currentfunctiondata(state);
  231. if (slot < 0 || slot >= JS_EVENT_SLOTS)
  232. return -1;
  233. return slot;
  234. }
  235. static void event_preventdefault(js_State *state)
  236. {
  237. int slot = event_slot(state);
  238. if (slot >= 0) {
  239. struct js_event_state *ev = &events[slot];
  240. ev->prevented = 1;
  241. if (ev->objref[0]) {
  242. js_getregistry(state, ev->objref);
  243. if (js_isobject(state, -1)) {
  244. js_pushboolean(state, 1);
  245. js_setproperty(state, -2, "defaultPrevented");
  246. }
  247. js_pop(state, 1);
  248. }
  249. }
  250. js_pushundefined(state);
  251. }
  252. static void event_stoppropagation(js_State *state)
  253. {
  254. int slot = event_slot(state);
  255. if (slot >= 0)
  256. events[slot].stopped = 1;
  257. js_pushundefined(state);
  258. }
  259. static void event_stopimmediate(js_State *state)
  260. {
  261. int slot = event_slot(state);
  262. if (slot >= 0) {
  263. events[slot].stopped = 1;
  264. events[slot].immediate = 1;
  265. }
  266. js_pushundefined(state);
  267. }
  268. /* Event-object field helpers. Every dispatch owns a registry key for its
  269. * event object so preventDefault can update the object without access to
  270. * `this` (the stack API has no this accessor). */
  271. static void ev_set_string(js_State *state, int slot, const char *name,
  272. const char *value)
  273. {
  274. js_getregistry(state, events[slot].objref);
  275. js_pushstring(state, value ? value : "");
  276. js_setproperty(state, -2, name);
  277. js_pop(state, 1);
  278. }
  279. static void ev_set_bool(js_State *state, int slot, const char *name, int value)
  280. {
  281. js_getregistry(state, events[slot].objref);
  282. js_pushboolean(state, value != 0);
  283. js_setproperty(state, -2, name);
  284. js_pop(state, 1);
  285. }
  286. static void ev_set_number(js_State *state, int slot, const char *name,
  287. double value)
  288. {
  289. js_getregistry(state, events[slot].objref);
  290. js_pushnumber(state, value);
  291. js_setproperty(state, -2, name);
  292. js_pop(state, 1);
  293. }
  294. static void ev_set_target(js_State *state, int slot, const char *name,
  295. unsigned int target)
  296. {
  297. js_getregistry(state, events[slot].objref);
  298. push_event_target(state, target);
  299. js_setproperty(state, -2, name);
  300. js_pop(state, 1);
  301. }
  302. static int ev_get_bool(js_State *state, int slot, const char *name, int def)
  303. {
  304. int rv = def;
  305. js_getregistry(state, events[slot].objref);
  306. js_getproperty(state, -1, name);
  307. if (js_isboolean(state, -1))
  308. rv = js_toboolean(state, -1);
  309. js_pop(state, 2);
  310. return rv;
  311. }
  312. static void ev_get_string(js_State *state, int slot, const char *name,
  313. char *out, int cap, const char *def)
  314. {
  315. const char *s = def ? def : "";
  316. int n = 0;
  317. js_getregistry(state, events[slot].objref);
  318. js_getproperty(state, -1, name);
  319. if (js_isstring(state, -1))
  320. s = js_tostring(state, -1);
  321. while (s[n] && n + 1 < cap) {
  322. out[n] = s[n];
  323. n++;
  324. }
  325. out[n] = '\0';
  326. js_pop(state, 2);
  327. }
  328. static void event_bind_methods(js_State *state, int slot)
  329. {
  330. js_getregistry(state, events[slot].objref);
  331. def_func_data(state, "preventDefault", event_preventdefault, 0,
  332. (unsigned int)slot);
  333. def_func_data(state, "stopPropagation", event_stoppropagation, 0,
  334. (unsigned int)slot);
  335. def_func_data(state, "stopImmediatePropagation", event_stopimmediate, 0,
  336. (unsigned int)slot);
  337. js_pop(state, 1);
  338. }
  339. /* The event object is on top of the stack; move it into the registry and
  340. * fill in the standard fields. */
  341. static int event_prepare(js_State *state, unsigned int target)
  342. {
  343. int slot;
  344. for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
  345. if (!events[slot].used)
  346. break;
  347. if (slot == JS_EVENT_SLOTS)
  348. return -1;
  349. events[slot].used = 1;
  350. events[slot].prevented = 0;
  351. events[slot].stopped = 0;
  352. events[slot].immediate = 0;
  353. snprintf(events[slot].objref, sizeof(events[slot].objref),
  354. "jseventobj_%d", slot);
  355. js_setregistry(state, events[slot].objref);
  356. ev_set_bool(state, slot, "defaultPrevented", 0);
  357. ev_set_bool(state, slot, "isTrusted", 0);
  358. ev_set_number(state, slot, "timeStamp", (double)u_ticks_ms());
  359. ev_set_target(state, slot, "target", target);
  360. ev_set_target(state, slot, "currentTarget", target);
  361. ev_set_number(state, slot, "eventPhase", 2);
  362. event_bind_methods(state, slot);
  363. return slot;
  364. }
  365. static int listener_call(js_State *state, const struct js_listener *l,
  366. int slot, unsigned int current_target)
  367. {
  368. js_getregistry(state, l->ref);
  369. if (!js_iscallable(state, -1)) {
  370. js_pop(state, 1);
  371. return 0;
  372. }
  373. push_event_target(state, current_target);
  374. js_getregistry(state, events[slot].objref);
  375. if (js_pcall(state, 1)) {
  376. report_top(state);
  377. return 0;
  378. }
  379. js_pop(state, 1);
  380. return 1;
  381. }
  382. static void listener_phase(js_State *state, unsigned int target,
  383. const char *type, int phase, int slot)
  384. {
  385. int i;
  386. for (i = 0; i < JS_LISTENERS; i++) {
  387. struct js_listener *l = &listeners[i];
  388. if (!l->used || l->target != target ||
  389. strcmp(l->type, type) != 0)
  390. continue;
  391. if (phase == 1 && !l->capture)
  392. continue;
  393. if (phase == 2 && l->capture)
  394. continue;
  395. ev_set_target(state, slot, "currentTarget", target);
  396. listener_call(state, l, slot, target);
  397. if (events[slot].immediate)
  398. return;
  399. }
  400. }
  401. /* supplied_idx: 0 creates a fresh object, otherwise it is the argument
  402. * index of an Event supplied by JavaScript. Leaves a boolean result. */
  403. static void inline_attr_decode(const char *s, char *d, unsigned int cap)
  404. {
  405. unsigned int i = 0, n = 0;
  406. while (s && s[i] && n + 1 < cap) {
  407. if (s[i] == '&') {
  408. if (!strncmp(s + i, "&quot;", 6)) {
  409. d[n++] = '"'; i += 6; continue;
  410. }
  411. if (!strncmp(s + i, "&#39;", 5)) {
  412. d[n++] = '\''; i += 5; continue;
  413. }
  414. if (!strncmp(s + i, "&amp;", 5)) {
  415. d[n++] = '&'; i += 5; continue;
  416. }
  417. if (!strncmp(s + i, "&lt;", 4)) {
  418. d[n++] = '<'; i += 4; continue;
  419. }
  420. if (!strncmp(s + i, "&gt;", 4)) {
  421. d[n++] = '>'; i += 4; continue;
  422. }
  423. }
  424. d[n++] = s[i++];
  425. }
  426. d[n] = '\0';
  427. }
  428. /* Inline on<event> attributes run at the target and while bubbling, after
  429. * the registered listeners for that node. The handler gets the event and
  430. * the element as `this`; a false return prevents the default action. */
  431. static void run_inline_handler(js_State *state, unsigned int node,
  432. const char *type, int slot, int *prevented)
  433. {
  434. char name[40], body[512], src[640];
  435. const char *attr;
  436. int truthy;
  437. if (!D || node >= D->nnode || !events[slot].objref[0])
  438. return;
  439. snprintf(name, sizeof(name), "on%s", type);
  440. attr = br_find_attr(D, node, name);
  441. if (!attr || !attr[0])
  442. return;
  443. inline_attr_decode(attr, body, sizeof(body));
  444. snprintf(src, sizeof(src), "(function(event){ %s\n})", body);
  445. if (js_try(state)) {
  446. /* The throw already unwound this try frame. */
  447. js_pop(state, 1);
  448. return;
  449. }
  450. js_loadstring(state, "[inline]", src);
  451. /* The script evaluates the function expression; run it first, then
  452. * call the resulting function with the element as `this`. */
  453. js_pushundefined(state);
  454. if (js_pcall(state, 0) || !js_iscallable(state, -1)) {
  455. js_pop(state, 1);
  456. js_endtry(state);
  457. return;
  458. }
  459. push_node(state, node + 1);
  460. js_getregistry(state, events[slot].objref);
  461. if (js_pcall(state, 1)) {
  462. js_pop(state, 1);
  463. js_endtry(state);
  464. return;
  465. }
  466. truthy = js_toboolean(state, -1);
  467. js_pop(state, 1);
  468. js_endtry(state);
  469. if (!truthy && prevented)
  470. *prevented = 1;
  471. }
  472. static int dispatch_object(js_State *state, unsigned int target,
  473. int supplied_idx, const char *fallback,
  474. int def_bubbles, int def_cancelable)
  475. {
  476. unsigned int path[64];
  477. char type[32];
  478. int np = 0, slot, i, prevented;
  479. struct br_node *nd;
  480. if (supplied_idx)
  481. js_copy(state, supplied_idx);
  482. else
  483. js_newobject(state);
  484. slot = event_prepare(state, target);
  485. if (slot < 0) {
  486. js_pushboolean(state, 1);
  487. return 1;
  488. }
  489. ev_get_string(state, slot, "type", type, sizeof(type), fallback);
  490. if (!type[0]) {
  491. js_unref(state, events[slot].objref);
  492. events[slot].objref[0] = '\0';
  493. events[slot].used = 0;
  494. js_pushboolean(state, 1);
  495. return 1;
  496. }
  497. ev_set_string(state, slot, "type", type);
  498. ev_set_bool(state, slot, "bubbles",
  499. ev_get_bool(state, slot, "bubbles", def_bubbles));
  500. ev_set_bool(state, slot, "cancelable",
  501. ev_get_bool(state, slot, "cancelable", def_cancelable));
  502. path[np++] = target;
  503. if (target != JS_TARGET_WINDOW && target != JS_TARGET_DOCUMENT &&
  504. D && target < D->nnode) {
  505. nd = &D->nodes[target];
  506. while (nd->parent && nd->parent < D->nnode &&
  507. np < (int)(sizeof(path) / sizeof(path[0]))) {
  508. path[np++] = nd->parent;
  509. nd = &D->nodes[nd->parent];
  510. }
  511. }
  512. if (target != JS_TARGET_WINDOW)
  513. path[np++] = JS_TARGET_DOCUMENT;
  514. if (target != JS_TARGET_WINDOW &&
  515. np < (int)(sizeof(path) / sizeof(path[0])))
  516. path[np++] = JS_TARGET_WINDOW;
  517. /* Capture from the outermost ancestor down to the parent. */
  518. for (i = np - 1; i > 0; i--) {
  519. if (events[slot].stopped)
  520. break;
  521. listener_phase(state, path[i], type, 1, slot);
  522. }
  523. /* Target phase: capture and bubble listeners in registration order. */
  524. if (!events[slot].stopped) {
  525. listener_phase(state, path[0], type, 0, slot);
  526. if (!events[slot].stopped)
  527. run_inline_handler(state, path[0], type, slot,
  528. &events[slot].prevented);
  529. }
  530. /* Bubble only for events that ask for it; stopPropagation stops the
  531. * remaining ancestors. */
  532. if (ev_get_bool(state, slot, "bubbles", def_bubbles)) {
  533. for (i = 1; i < np && !events[slot].stopped; i++) {
  534. listener_phase(state, path[i], type, 2, slot);
  535. if (!events[slot].stopped &&
  536. path[i] != JS_TARGET_WINDOW &&
  537. path[i] != JS_TARGET_DOCUMENT)
  538. run_inline_handler(state, path[i], type, slot,
  539. &events[slot].prevented);
  540. }
  541. }
  542. prevented = events[slot].prevented;
  543. js_unref(state, events[slot].objref);
  544. events[slot].objref[0] = '\0';
  545. events[slot].used = 0;
  546. js_pushboolean(state, prevented ? 0 : 1);
  547. return prevented ? 0 : 1;
  548. }
  549. static void add_listener(js_State *state, unsigned int target, int remove)
  550. {
  551. const char *type;
  552. int i;
  553. if (!js_iscallable(state, 2))
  554. return;
  555. type = js_tostring(state, 1);
  556. if (!type[0])
  557. return;
  558. if (!remove) {
  559. for (i = 0; i < JS_LISTENERS; i++)
  560. if (!listeners[i].used)
  561. break;
  562. if (i == JS_LISTENERS)
  563. return;
  564. listeners[i].used = 1;
  565. listeners[i].capture = js_isboolean(state, 3) &&
  566. js_toboolean(state, 3);
  567. listeners[i].target = target;
  568. snprintf(listeners[i].type, sizeof(listeners[i].type), "%s",
  569. type);
  570. js_copy(state, 2);
  571. snprintf(listeners[i].ref, sizeof(listeners[i].ref), "%s",
  572. js_ref(state));
  573. return;
  574. }
  575. for (i = 0; i < JS_LISTENERS; i++) {
  576. struct js_listener *l = &listeners[i];
  577. int eq;
  578. if (!l->used || l->target != target ||
  579. strcmp(l->type, type) != 0)
  580. continue;
  581. js_getregistry(state, l->ref);
  582. js_copy(state, 2);
  583. eq = js_equal(state);
  584. js_pop(state, 2);
  585. if (!eq)
  586. continue;
  587. js_unref(state, l->ref);
  588. l->used = 0;
  589. return;
  590. }
  591. }
  592. static void node_addlistener(js_State *state)
  593. {
  594. unsigned int node = (unsigned int)(uintptr_t)
  595. js_currentfunctiondata(state) - 1;
  596. add_listener(state, node, 0);
  597. }
  598. static void node_removelistener(js_State *state)
  599. {
  600. unsigned int node = (unsigned int)(uintptr_t)
  601. js_currentfunctiondata(state) - 1;
  602. add_listener(state, node, 1);
  603. }
  604. static void node_dispatchevent(js_State *state)
  605. {
  606. unsigned int node = (unsigned int)(uintptr_t)
  607. js_currentfunctiondata(state) - 1;
  608. if (!D || !node) {
  609. js_pushboolean(state, 1);
  610. return;
  611. }
  612. if (js_isobject(state, 1)) {
  613. dispatch_object(state, node, 1, "event", 1, 0);
  614. } else {
  615. char type[32];
  616. const char *s = js_tostring(state, 1);
  617. unsigned int i = 0;
  618. while (s[i] && i + 1 < sizeof(type)) {
  619. type[i] = s[i];
  620. i++;
  621. }
  622. type[i] = '\0';
  623. dispatch_object(state, node, 0, type, 1, 0);
  624. }
  625. }
  626. static void win_addlistener(js_State *state)
  627. {
  628. add_listener(state, JS_TARGET_WINDOW, 0);
  629. }
  630. static void win_removelistener(js_State *state)
  631. {
  632. add_listener(state, JS_TARGET_WINDOW, 1);
  633. }
  634. static void doc_addlistener(js_State *state)
  635. {
  636. add_listener(state, JS_TARGET_DOCUMENT, 0);
  637. }
  638. static void doc_removelistener(js_State *state)
  639. {
  640. add_listener(state, JS_TARGET_DOCUMENT, 1);
  641. }
  642. static void event_init(js_State *state)
  643. {
  644. int slot = (int)(uintptr_t)js_currentfunctiondata(state);
  645. const char *type;
  646. if (slot < 0 || slot >= JS_EVENT_TEMPLATES ||
  647. !event_templates[slot].used)
  648. return;
  649. type = js_tostring(state, 1);
  650. js_getregistry(state, event_templates[slot].ref);
  651. if (!js_isobject(state, -1)) {
  652. js_pop(state, 1);
  653. return;
  654. }
  655. obj_set_string(state, -1, "type", type);
  656. obj_set_bool(state, -1, "bubbles", js_toboolean(state, 2));
  657. obj_set_bool(state, -1, "cancelable", js_toboolean(state, 3));
  658. js_pop(state, 1);
  659. }
  660. static void event_build_object(js_State *state, const char *type,
  661. int bubbles, int cancelable, int with_init)
  662. {
  663. js_newobject(state);
  664. js_pushstring(state, type ? type : "");
  665. js_setproperty(state, -2, "type");
  666. js_pushboolean(state, bubbles != 0);
  667. js_setproperty(state, -2, "bubbles");
  668. js_pushboolean(state, cancelable != 0);
  669. js_setproperty(state, -2, "cancelable");
  670. js_pushboolean(state, 0);
  671. js_setproperty(state, -2, "defaultPrevented");
  672. if (with_init) {
  673. int i;
  674. for (i = 0; i < JS_EVENT_TEMPLATES; i++)
  675. if (!event_templates[i].used)
  676. break;
  677. if (i < JS_EVENT_TEMPLATES) {
  678. event_templates[i].used = 1;
  679. snprintf(event_templates[i].ref,
  680. sizeof(event_templates[i].ref),
  681. "jseventtmpl_%d", i);
  682. js_copy(state, -1);
  683. js_setregistry(state, event_templates[i].ref);
  684. def_func_data(state, "initEvent", event_init, 3,
  685. (unsigned int)i);
  686. }
  687. }
  688. }
  689. static void event_call(js_State *state)
  690. {
  691. const char *type = js_isdefined(state, 1) ? js_tostring(state, 1) : "";
  692. int bubbles = 0, cancelable = 0;
  693. if (js_isobject(state, 2)) {
  694. js_getproperty(state, 2, "bubbles");
  695. bubbles = js_toboolean(state, -1);
  696. js_pop(state, 1);
  697. js_getproperty(state, 2, "cancelable");
  698. cancelable = js_toboolean(state, -1);
  699. js_pop(state, 1);
  700. }
  701. event_build_object(state, type, bubbles, cancelable, 1);
  702. }
  703. static void doc_createevent(js_State *state)
  704. {
  705. const char *type = js_tostring(state, 1);
  706. event_build_object(state, type, 0, 0, 1);
  707. }
  708. static void custom_event_call(js_State *state)
  709. {
  710. event_call(state);
  711. if (js_isobject(state, 2))
  712. js_getproperty(state, 2, "detail");
  713. else
  714. js_pushnull(state);
  715. js_setproperty(state, -2, "detail");
  716. }
  717. static void mouse_event_call(js_State *state)
  718. {
  719. static const struct {
  720. const char *name;
  721. int is_number;
  722. } props[] = {
  723. { "clientX", 1 }, { "clientY", 1 }, { "screenX", 1 },
  724. { "screenY", 1 }, { "button", 1 }, { "buttons", 1 },
  725. { "ctrlKey", 0 }, { "shiftKey", 0 }, { "altKey", 0 },
  726. { "metaKey", 0 }
  727. };
  728. unsigned int i;
  729. event_call(state);
  730. if (!js_isobject(state, 2))
  731. return;
  732. for (i = 0; i < sizeof(props) / sizeof(props[0]); i++) {
  733. js_getproperty(state, 2, props[i].name);
  734. if (props[i].is_number) {
  735. double v = js_isnumber(state, -1) ?
  736. js_tonumber(state, -1) : 0;
  737. js_pop(state, 1);
  738. js_pushnumber(state, v);
  739. } else {
  740. int v = js_toboolean(state, -1);
  741. js_pop(state, 1);
  742. js_pushboolean(state, v);
  743. }
  744. js_setproperty(state, -2, props[i].name);
  745. }
  746. }
  747. int js_browser_event(unsigned int node, const char *type, int bubbles,
  748. int cancelable)
  749. {
  750. int slot, rv;
  751. if (!J || !D)
  752. return 1;
  753. for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
  754. if (!events[slot].used)
  755. break;
  756. if (slot == JS_EVENT_SLOTS)
  757. return 1;
  758. js_setlimit(J, JS_RUN_LIMIT, 0);
  759. rv = dispatch_object(J, node, 0, type, bubbles, cancelable);
  760. js_pop(J, 1);
  761. js_runjobs(J);
  762. return rv;
  763. }
  764. static unsigned int node_type_value(unsigned int node)
  765. {
  766. struct br_node *n;
  767. if (!D || node >= D->nnode)
  768. return 0;
  769. n = &D->nodes[node];
  770. if (n->type == BR_NODE_TEXT)
  771. return 3;
  772. if (n->type == BR_NODE_COMMENT)
  773. return 8;
  774. if (n->type == BR_NODE_FRAGMENT)
  775. return 11;
  776. return 1;
  777. }
  778. static void push_child_list(js_State *state, unsigned int node, int elements)
  779. {
  780. struct br_node *n;
  781. unsigned int c, i = 0;
  782. js_newarray(state);
  783. if (!D || node >= D->nnode)
  784. return;
  785. n = &D->nodes[node];
  786. for (c = n->first; c; c = D->nodes[c].next) {
  787. if (elements && D->nodes[c].type != BR_NODE_ELEM)
  788. continue;
  789. push_node(state, c + 1);
  790. js_setindex(state, -2, (int)i++);
  791. }
  792. }
  793. static unsigned int node_prev_sibling(unsigned int node)
  794. {
  795. unsigned int p, c, prev = 0;
  796. if (!D || node >= D->nnode)
  797. return 0;
  798. p = D->nodes[node].parent;
  799. for (c = D->nodes[p].first; c && c != node; c = D->nodes[c].next)
  800. prev = c;
  801. return prev;
  802. }
  803. /* ---- inline style and dataset objects ---- */
  804. static int ci_eq_n(const char *a, const char *b, unsigned int n)
  805. {
  806. unsigned int i;
  807. for (i = 0; i < n; i++) {
  808. char ca = a[i], cb = b[i];
  809. if (ca >= 'A' && ca <= 'Z')
  810. ca = (char)(ca - 'A' + 'a');
  811. if (cb >= 'A' && cb <= 'Z')
  812. cb = (char)(cb - 'A' + 'a');
  813. if (ca != cb)
  814. return 0;
  815. }
  816. return 1;
  817. }
  818. /* camelCase JS property -> CSS property ("marginTop" -> "margin-top"). */
  819. static void css_name(const char *name, char *out, unsigned int cap)
  820. {
  821. unsigned int n = 0, i;
  822. if (!strcmp(name, "cssFloat")) {
  823. if (cap > 6)
  824. memcpy(out, "float", 6);
  825. else if (cap)
  826. out[0] = '\0';
  827. return;
  828. }
  829. for (i = 0; name[i] && n + 2 < cap; i++) {
  830. char c = name[i];
  831. if (c >= 'A' && c <= 'Z') {
  832. if (n == 0 || out[n - 1] != '-')
  833. out[n++] = '-';
  834. out[n++] = (char)(c - 'A' + 'a');
  835. } else {
  836. out[n++] = c;
  837. }
  838. }
  839. if (cap)
  840. out[n] = '\0';
  841. }
  842. /* camelCase dataset property -> attribute name ("fooBar" -> "data-foo-bar"). */
  843. static void data_name(const char *name, char *out, unsigned int cap)
  844. {
  845. unsigned int n = 0, i;
  846. for (i = 0; i < 5 && n + 1 < cap; i++)
  847. out[n++] = "data-"[i];
  848. for (i = 0; name[i] && n + 2 < cap; i++) {
  849. char c = name[i];
  850. if (c >= 'A' && c <= 'Z') {
  851. out[n++] = '-';
  852. c = (char)(c - 'A' + 'a');
  853. }
  854. out[n++] = c;
  855. }
  856. if (cap)
  857. out[n] = '\0';
  858. }
  859. static int style_lookup(const char *style, const char *prop, char *out,
  860. unsigned int cap)
  861. {
  862. unsigned int i = 0, nl = (unsigned int)strlen(prop);
  863. while (style && style[i]) {
  864. unsigned int ns, ne, vs, ve, a, b, k;
  865. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  866. i++;
  867. if (!style[i])
  868. break;
  869. ns = i;
  870. while (style[i] && style[i] != ':' && style[i] != ';')
  871. i++;
  872. ne = i;
  873. if (style[i] != ':') {
  874. if (style[i] == ';')
  875. i++;
  876. continue;
  877. }
  878. i++;
  879. while (style[i] == ' ' || style[i] == '\t')
  880. i++;
  881. vs = i;
  882. while (style[i] && style[i] != ';')
  883. i++;
  884. ve = i;
  885. a = ns;
  886. b = ne;
  887. while (a < b && (style[a] == ' ' || style[a] == '\t'))
  888. a++;
  889. while (b > a && (style[b - 1] == ' ' || style[b - 1] == '\t'))
  890. b--;
  891. while (ve > vs && (style[ve - 1] == ' ' || style[ve - 1] == '\t'))
  892. ve--;
  893. if (b - a == nl && ci_eq_n(style + a, prop, nl)) {
  894. for (k = 0; k < ve - vs && k + 1 < cap; k++)
  895. out[k] = style[vs + k];
  896. out[k < cap ? k : cap - 1] = '\0';
  897. return 1;
  898. }
  899. }
  900. return 0;
  901. }
  902. static unsigned int style_count(const char *style)
  903. {
  904. unsigned int i = 0, n = 0;
  905. while (style && style[i]) {
  906. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  907. i++;
  908. if (!style[i])
  909. break;
  910. while (style[i] && style[i] != ';')
  911. i++;
  912. n++;
  913. }
  914. return n;
  915. }
  916. static unsigned int style_span(const char *style, unsigned int i)
  917. {
  918. while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
  919. i++;
  920. return i;
  921. }
  922. static void style_update(unsigned int node, const char *prop,
  923. const char *value, int remove)
  924. {
  925. const char *old = br_find_attr(D, node, "style");
  926. char arr[512];
  927. unsigned int n = 0, i = 0, nl = (unsigned int)strlen(prop);
  928. int replaced = 0;
  929. if (remove && !old)
  930. return;
  931. while (old && old[i] && n + 2 < sizeof(arr)) {
  932. unsigned int start = style_span(old, i);
  933. unsigned int ns, ne, ve, a, b, k;
  934. i = start;
  935. if (!old[i])
  936. break;
  937. ns = i;
  938. while (old[i] && old[i] != ':' && old[i] != ';')
  939. i++;
  940. ne = i;
  941. if (old[i] == ':') {
  942. i++;
  943. while (old[i] == ' ' || old[i] == '\t')
  944. i++;
  945. while (old[i] && old[i] != ';')
  946. i++;
  947. }
  948. ve = i;
  949. a = ns;
  950. b = ne;
  951. while (a < b && (old[a] == ' ' || old[a] == '\t'))
  952. a++;
  953. while (b > a && (old[b - 1] == ' ' || old[b - 1] == '\t'))
  954. b--;
  955. if (b - a == nl && ci_eq_n(old + a, prop, nl)) {
  956. replaced = 1;
  957. if (remove || !value || !value[0])
  958. continue;
  959. }
  960. for (k = ns; k < ve && n + 1 < sizeof(arr); k++)
  961. arr[n++] = old[k];
  962. if (n + 1 < sizeof(arr))
  963. arr[n++] = ';';
  964. }
  965. if (replaced && (remove || !value || !value[0])) {
  966. arr[n] = '\0';
  967. br_set_attr(D, node, "style", arr, n);
  968. if (host.changed)
  969. host.changed();
  970. return;
  971. }
  972. if (value && value[0] && n + nl + strlen(value) + 3 < sizeof(arr)) {
  973. for (i = 0; i < nl; i++)
  974. arr[n++] = prop[i];
  975. arr[n++] = ':';
  976. for (i = 0; value[i]; i++)
  977. arr[n++] = value[i];
  978. arr[n++] = ';';
  979. }
  980. arr[n] = '\0';
  981. br_set_attr(D, node, "style", arr, n);
  982. if (host.changed)
  983. host.changed();
  984. }
  985. static void style_getproperty(js_State *state)
  986. {
  987. unsigned int node = node_of(js_currentfunctiondata(state));
  988. char val[256];
  989. if (style_lookup(br_find_attr(D, node, "style"),
  990. js_tostring(state, 1), val, sizeof(val)))
  991. js_pushstring(state, val);
  992. else
  993. js_pushstring(state, "");
  994. }
  995. static void style_setproperty(js_State *state)
  996. {
  997. unsigned int node = node_of(js_currentfunctiondata(state));
  998. style_update(node, js_tostring(state, 1),
  999. js_tostring(state, 2), 0);
  1000. }
  1001. static void style_removeproperty(js_State *state)
  1002. {
  1003. unsigned int node = node_of(js_currentfunctiondata(state));
  1004. const char *prop = js_tostring(state, 1);
  1005. char old[256];
  1006. int had = style_lookup(br_find_attr(D, node, "style"), prop,
  1007. old, sizeof(old));
  1008. style_update(node, prop, "", 1);
  1009. if (had)
  1010. js_pushstring(state, old);
  1011. else
  1012. js_pushstring(state, "");
  1013. }
  1014. static int style_has(js_State *state, void *p, const char *name)
  1015. {
  1016. unsigned int node = node_of(p);
  1017. const char *style;
  1018. char prop[64], val[256];
  1019. if (!D || node >= D->nnode)
  1020. return 0;
  1021. style = br_find_attr(D, node, "style");
  1022. if (!strcmp(name, "cssText")) {
  1023. js_pushstring(state, style ? style : "");
  1024. return 1;
  1025. }
  1026. if (!strcmp(name, "length")) {
  1027. js_pushnumber(state, style_count(style));
  1028. return 1;
  1029. }
  1030. if (!strcmp(name, "getPropertyValue")) {
  1031. push_func_data(state, name, style_getproperty, 1, node + 1);
  1032. return 1;
  1033. }
  1034. if (!strcmp(name, "setProperty")) {
  1035. push_func_data(state, name, style_setproperty, 2, node + 1);
  1036. return 1;
  1037. }
  1038. if (!strcmp(name, "removeProperty")) {
  1039. push_func_data(state, name, style_removeproperty, 1, node + 1);
  1040. return 1;
  1041. }
  1042. css_name(name, prop, sizeof(prop));
  1043. if (style_lookup(style, prop, val, sizeof(val)))
  1044. js_pushstring(state, val);
  1045. else
  1046. js_pushstring(state, "");
  1047. return 1;
  1048. }
  1049. static int style_put(js_State *state, void *p, const char *name)
  1050. {
  1051. unsigned int node = node_of(p);
  1052. const char *value;
  1053. char prop[64];
  1054. if (!D || node >= D->nnode)
  1055. return 0;
  1056. value = js_tostring(state, -1);
  1057. if (!strcmp(name, "cssText")) {
  1058. br_set_attr(D, node, "style", value, (unsigned int)strlen(value));
  1059. if (host.changed)
  1060. host.changed();
  1061. return 1;
  1062. }
  1063. css_name(name, prop, sizeof(prop));
  1064. style_update(node, prop, value, 0);
  1065. return 1;
  1066. }
  1067. static void push_style_object(js_State *state, unsigned int node)
  1068. {
  1069. char key[32];
  1070. snprintf(key, sizeof(key), "sty_%u", node + 1);
  1071. js_getregistry(state, key);
  1072. if (!js_isundefined(state, -1))
  1073. return;
  1074. js_pop(state, 1);
  1075. js_getregistry(state, "wrapproto");
  1076. js_newuserdatax(state, "style", (void *)(uintptr_t)(node + 1),
  1077. style_has, style_put, 0, 0);
  1078. js_copy(state, -1);
  1079. js_setregistry(state, key);
  1080. }
  1081. static int dataset_has(js_State *state, void *p, const char *name)
  1082. {
  1083. unsigned int node = node_of(p);
  1084. char attr[64];
  1085. const char *value;
  1086. if (!D || node >= D->nnode)
  1087. return 0;
  1088. data_name(name, attr, sizeof(attr));
  1089. value = br_find_attr(D, node, attr);
  1090. if (value)
  1091. js_pushstring(state, value);
  1092. else
  1093. js_pushundefined(state);
  1094. return 1;
  1095. }
  1096. static int dataset_put(js_State *state, void *p, const char *name)
  1097. {
  1098. unsigned int node = node_of(p);
  1099. char attr[64];
  1100. const char *value = js_tostring(state, -1);
  1101. if (!D || node >= D->nnode)
  1102. return 0;
  1103. data_name(name, attr, sizeof(attr));
  1104. br_set_attr(D, node, attr, value, (unsigned int)strlen(value));
  1105. if (host.changed)
  1106. host.changed();
  1107. return 1;
  1108. }
  1109. static int dataset_delete(js_State *state, void *p, const char *name)
  1110. {
  1111. unsigned int node = node_of(p);
  1112. char attr[64];
  1113. (void)state;
  1114. if (!D || node >= D->nnode)
  1115. return 0;
  1116. data_name(name, attr, sizeof(attr));
  1117. br_remove_attr(D, node, attr);
  1118. if (host.changed)
  1119. host.changed();
  1120. return 1;
  1121. }
  1122. static void push_dataset(js_State *state, unsigned int node)
  1123. {
  1124. char key[32];
  1125. snprintf(key, sizeof(key), "ds_%u", node + 1);
  1126. js_getregistry(state, key);
  1127. if (!js_isundefined(state, -1))
  1128. return;
  1129. js_pop(state, 1);
  1130. js_getregistry(state, "wrapproto");
  1131. js_newuserdatax(state, "dataset", (void *)(uintptr_t)(node + 1),
  1132. dataset_has, dataset_put, dataset_delete, 0);
  1133. js_copy(state, -1);
  1134. js_setregistry(state, key);
  1135. }
  1136. static void node_class_set(unsigned int node, const char *classes)
  1137. {
  1138. br_set_attr(D, node, "class", classes,
  1139. (unsigned int)strlen(classes));
  1140. if (host.changed)
  1141. host.changed();
  1142. }
  1143. static int class_has(const char *classes, const char *name)
  1144. {
  1145. unsigned int i = 0;
  1146. if (!classes)
  1147. return 0;
  1148. while (classes[i]) {
  1149. unsigned int start;
  1150. while (classes[i] == ' ' || classes[i] == '\t')
  1151. i++;
  1152. start = i;
  1153. while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
  1154. i++;
  1155. if (i - start == strlen(name) &&
  1156. !strncmp(classes + start, name, i - start))
  1157. return 1;
  1158. }
  1159. return 0;
  1160. }
  1161. static void class_add(unsigned int node, const char *name, int add)
  1162. {
  1163. const char *old = node_attr(node, "class");
  1164. char buf[256];
  1165. unsigned int n = 0, i = 0;
  1166. if (add) {
  1167. if (class_has(old, name))
  1168. return;
  1169. if (old && old[0]) {
  1170. while (old[i] && n + 1 < sizeof(buf))
  1171. buf[n++] = old[i++];
  1172. if (n + 1 < sizeof(buf))
  1173. buf[n++] = ' ';
  1174. }
  1175. i = 0;
  1176. while (name[i] && n + 1 < sizeof(buf))
  1177. buf[n++] = name[i++];
  1178. } else {
  1179. if (!old)
  1180. return;
  1181. while (old[i]) {
  1182. unsigned int start;
  1183. while (old[i] == ' ' || old[i] == '\t')
  1184. i++;
  1185. start = i;
  1186. while (old[i] && old[i] != ' ' && old[i] != '\t')
  1187. i++;
  1188. if (i - start == strlen(name) &&
  1189. !strncmp(old + start, name, i - start))
  1190. continue;
  1191. if (n && n + 1 < sizeof(buf))
  1192. buf[n++] = ' ';
  1193. {
  1194. unsigned int k;
  1195. for (k = start; k < i && n + 1 < sizeof(buf);
  1196. k++)
  1197. buf[n++] = old[k];
  1198. }
  1199. }
  1200. }
  1201. buf[n] = '\0';
  1202. node_class_set(node, buf);
  1203. }
  1204. static void node_classlist_add(js_State *state)
  1205. {
  1206. class_add(node_of(js_currentfunctiondata(state)),
  1207. js_tostring(state, 1), 1);
  1208. }
  1209. static void node_classlist_remove(js_State *state)
  1210. {
  1211. class_add(node_of(js_currentfunctiondata(state)),
  1212. js_tostring(state, 1), 0);
  1213. }
  1214. static void node_classlist_toggle(js_State *state)
  1215. {
  1216. unsigned int node = node_of(js_currentfunctiondata(state));
  1217. const char *name = js_tostring(state, 1);
  1218. int has = class_has(node_attr(node, "class"), name);
  1219. int want = !has;
  1220. if (js_isdefined(state, 2))
  1221. want = js_toboolean(state, 2);
  1222. if (want != has)
  1223. class_add(node, name, want);
  1224. js_pushboolean(state, want);
  1225. }
  1226. static void node_classlist_contains(js_State *state)
  1227. {
  1228. unsigned int node = node_of(js_currentfunctiondata(state));
  1229. js_pushboolean(state, class_has(node_attr(node, "class"),
  1230. js_tostring(state, 1)));
  1231. }
  1232. static unsigned int class_count(const char *classes)
  1233. {
  1234. unsigned int i = 0, n = 0;
  1235. if (!classes)
  1236. return 0;
  1237. while (classes[i]) {
  1238. while (classes[i] == ' ' || classes[i] == '\t')
  1239. i++;
  1240. if (!classes[i])
  1241. break;
  1242. n++;
  1243. while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
  1244. i++;
  1245. }
  1246. return n;
  1247. }
  1248. static void push_attributes(js_State *state, unsigned int node)
  1249. {
  1250. struct br_node *n;
  1251. const char *p, *end;
  1252. unsigned int count = 0;
  1253. js_newobject(state);
  1254. if (!D || node >= D->nnode)
  1255. return;
  1256. n = &D->nodes[node];
  1257. p = D->attrs + n->extra_off;
  1258. end = p + n->extra_len;
  1259. while (p + 1 < end) {
  1260. const char *an = p;
  1261. const char *av;
  1262. p += strlen(p) + 1;
  1263. if (p >= end)
  1264. break;
  1265. av = p;
  1266. p += strlen(p) + 1;
  1267. js_newobject(state);
  1268. js_pushstring(state, an);
  1269. js_setproperty(state, -2, "name");
  1270. js_pushstring(state, av);
  1271. js_setproperty(state, -2, "value");
  1272. js_pushboolean(state, 1);
  1273. js_setproperty(state, -2, "specified");
  1274. /* Array-like: attributes[i] and attributes[name] both work. */
  1275. js_copy(state, -1);
  1276. js_setproperty(state, -3, an);
  1277. js_setindex(state, -2, (int)count);
  1278. count++;
  1279. }
  1280. js_pushnumber(state, count);
  1281. js_setproperty(state, -2, "length");
  1282. }
  1283. static void push_classlist(js_State *state, unsigned int node)
  1284. {
  1285. js_newobject(state);
  1286. def_func_data(state, "add", node_classlist_add, 1, node + 1);
  1287. def_func_data(state, "remove", node_classlist_remove, 1, node + 1);
  1288. def_func_data(state, "toggle", node_classlist_toggle, 1, node + 1);
  1289. def_func_data(state, "contains", node_classlist_contains, 1, node + 1);
  1290. js_pushnumber(state, class_count(node_attr(node, "class")));
  1291. js_setproperty(state, -2, "length");
  1292. }
  1293. static void node_getattr(js_State *state)
  1294. {
  1295. unsigned int node = node_of(js_currentfunctiondata(state));
  1296. push_attr(state, node, js_tostring(state, 1), 1);
  1297. }
  1298. static void node_setattr(js_State *state)
  1299. {
  1300. unsigned int node = node_of(js_currentfunctiondata(state));
  1301. const char *name = js_tostring(state, 1);
  1302. const char *value = js_tostring(state, 2);
  1303. char lower[64];
  1304. unsigned int i;
  1305. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  1306. char c = name[i];
  1307. if (c >= 'A' && c <= 'Z')
  1308. c = (char)(c - 'A' + 'a');
  1309. lower[i] = c;
  1310. }
  1311. lower[i] = '\0';
  1312. br_set_attr(D, node, lower, value, (unsigned int)strlen(value));
  1313. if (host.changed)
  1314. host.changed();
  1315. }
  1316. static void node_removeattr(js_State *state)
  1317. {
  1318. unsigned int node = node_of(js_currentfunctiondata(state));
  1319. const char *name = js_tostring(state, 1);
  1320. char lower[64];
  1321. unsigned int i;
  1322. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  1323. char c = name[i];
  1324. if (c >= 'A' && c <= 'Z')
  1325. c = (char)(c - 'A' + 'a');
  1326. lower[i] = c;
  1327. }
  1328. lower[i] = '\0';
  1329. br_remove_attr(D, node, lower);
  1330. if (host.changed)
  1331. host.changed();
  1332. }
  1333. static void node_hasattr(js_State *state)
  1334. {
  1335. unsigned int node = node_of(js_currentfunctiondata(state));
  1336. js_pushboolean(state, node_attr(node, js_tostring(state, 1)) != 0);
  1337. }
  1338. static void node_appendchild(js_State *state)
  1339. {
  1340. unsigned int node = node_of(js_currentfunctiondata(state));
  1341. unsigned int child = arg_node(state, 1);
  1342. if (br_append_child(D, node, child) != 0) {
  1343. js_pushnull(state);
  1344. return;
  1345. }
  1346. if (host.changed)
  1347. host.changed();
  1348. push_node(state, child);
  1349. }
  1350. static void node_insertbefore(js_State *state)
  1351. {
  1352. unsigned int node = node_of(js_currentfunctiondata(state));
  1353. unsigned int child = arg_node(state, 1);
  1354. unsigned int before = 0;
  1355. if (!js_isnull(state, 2) && !js_isundefined(state, 2))
  1356. before = arg_node(state, 2);
  1357. if (br_insert_before(D, node, child, before) != 0) {
  1358. js_pushnull(state);
  1359. return;
  1360. }
  1361. if (host.changed)
  1362. host.changed();
  1363. push_node(state, child);
  1364. }
  1365. static void node_removechild(js_State *state)
  1366. {
  1367. unsigned int node = node_of(js_currentfunctiondata(state));
  1368. unsigned int child = arg_node(state, 1);
  1369. if (br_remove_child(D, node, child) != 0) {
  1370. js_pushnull(state);
  1371. return;
  1372. }
  1373. if (host.changed)
  1374. host.changed();
  1375. push_node(state, child);
  1376. }
  1377. static void node_replacechild(js_State *state)
  1378. {
  1379. unsigned int node = node_of(js_currentfunctiondata(state));
  1380. unsigned int child = arg_node(state, 1);
  1381. unsigned int old = arg_node(state, 2);
  1382. br_insert_before(D, node, child, old);
  1383. br_remove_child(D, node, old);
  1384. if (host.changed)
  1385. host.changed();
  1386. push_node(state, old);
  1387. }
  1388. static void node_clone(js_State *state)
  1389. {
  1390. unsigned int node = node_of(js_currentfunctiondata(state));
  1391. unsigned int h = br_clone_node(D, node + 1,
  1392. js_toboolean(state, 1));
  1393. push_node(state, h);
  1394. }
  1395. static void node_contains(js_State *state)
  1396. {
  1397. unsigned int node = node_of(js_currentfunctiondata(state));
  1398. unsigned int other = arg_node(state, 1);
  1399. unsigned int p = other;
  1400. while (1) {
  1401. if (p == node) {
  1402. js_pushboolean(state, 1);
  1403. return;
  1404. }
  1405. if (p == 0)
  1406. break;
  1407. p = D->nodes[p].parent;
  1408. }
  1409. js_pushboolean(state, 0);
  1410. }
  1411. static void node_haschildren(js_State *state)
  1412. {
  1413. unsigned int node = node_of(js_currentfunctiondata(state));
  1414. js_pushboolean(state, node < D->nnode && D->nodes[node].first != 0);
  1415. }
  1416. static void node_remove(js_State *state)
  1417. {
  1418. unsigned int node = node_of(js_currentfunctiondata(state));
  1419. unsigned int parent = node < D->nnode ? D->nodes[node].parent : 0;
  1420. (void)state;
  1421. if (parent)
  1422. br_remove_child(D, parent, node + 1);
  1423. if (host.changed)
  1424. host.changed();
  1425. }
  1426. static void node_matches(js_State *state)
  1427. {
  1428. unsigned int node = node_of(js_currentfunctiondata(state));
  1429. js_pushboolean(state, br_matches(D, node + 1,
  1430. js_tostring(state, 1)));
  1431. }
  1432. static void node_click(js_State *state)
  1433. {
  1434. unsigned int node = node_of(js_currentfunctiondata(state));
  1435. if (host.click)
  1436. host.click(node);
  1437. js_pushundefined(state);
  1438. }
  1439. static void node_getelementsbytagname(js_State *state)
  1440. {
  1441. unsigned int node = node_of(js_currentfunctiondata(state));
  1442. const char *name = js_tostring(state, 1);
  1443. unsigned int out[256];
  1444. unsigned int n = br_query_all(D, node + 1, name, out, 256);
  1445. js_newarray(state);
  1446. for (unsigned int i = 0; i < n; i++) {
  1447. push_node(state, out[i]);
  1448. js_setindex(state, -2, (int)i);
  1449. }
  1450. }
  1451. static void node_getelementsbyclassname(js_State *state)
  1452. {
  1453. unsigned int node = node_of(js_currentfunctiondata(state));
  1454. const char *name = js_tostring(state, 1);
  1455. char sel[256];
  1456. unsigned int n = 0, i = 0;
  1457. unsigned int out[256], count;
  1458. while (name[i] && n + 2 < sizeof(sel)) {
  1459. while (name[i] == ' ')
  1460. i++;
  1461. if (!name[i])
  1462. break;
  1463. sel[n++] = '.';
  1464. while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
  1465. sel[n++] = name[i++];
  1466. }
  1467. sel[n] = '\0';
  1468. count = br_query_all(D, node + 1, sel, out, 256);
  1469. js_newarray(state);
  1470. for (i = 0; i < count; i++) {
  1471. push_node(state, out[i]);
  1472. js_setindex(state, -2, (int)i);
  1473. }
  1474. }
  1475. static void node_queryselector(js_State *state)
  1476. {
  1477. unsigned int node = node_of(js_currentfunctiondata(state));
  1478. unsigned int out[1];
  1479. unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
  1480. out, 1);
  1481. if (n)
  1482. push_node(state, out[0]);
  1483. else
  1484. js_pushnull(state);
  1485. }
  1486. static void node_queryselectorall(js_State *state)
  1487. {
  1488. unsigned int node = node_of(js_currentfunctiondata(state));
  1489. unsigned int out[256];
  1490. unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
  1491. out, 256);
  1492. js_newarray(state);
  1493. for (unsigned int i = 0; i < n; i++) {
  1494. push_node(state, out[i]);
  1495. js_setindex(state, -2, (int)i);
  1496. }
  1497. }
  1498. static void node_getrect(js_State *state)
  1499. {
  1500. unsigned int node = node_of(js_currentfunctiondata(state));
  1501. int x = 0, y = 0, w = 0, h = 0;
  1502. if (host.rect)
  1503. host.rect(node, &x, &y, &w, &h);
  1504. js_newobject(state);
  1505. js_pushnumber(state, y); js_setproperty(state, -2, "top");
  1506. js_pushnumber(state, x); js_setproperty(state, -2, "left");
  1507. js_pushnumber(state, x + w); js_setproperty(state, -2, "right");
  1508. js_pushnumber(state, y + h); js_setproperty(state, -2, "bottom");
  1509. js_pushnumber(state, w); js_setproperty(state, -2, "width");
  1510. js_pushnumber(state, h); js_setproperty(state, -2, "height");
  1511. }
  1512. static void node_noop(js_State *state)
  1513. {
  1514. (void)state;
  1515. }
  1516. static void node_push_text(js_State *state, unsigned int node)
  1517. {
  1518. unsigned int cap = D->text_used + 1;
  1519. char *buf;
  1520. unsigned int len;
  1521. if (cap < 32)
  1522. cap = 32;
  1523. buf = (char *)malloc(cap);
  1524. if (!buf) {
  1525. js_pushstring(state, "");
  1526. return;
  1527. }
  1528. len = br_text_content(D, node, buf, cap);
  1529. js_pushlstring(state, buf, (int)len);
  1530. free(buf);
  1531. }
  1532. static unsigned int node_form_ancestor(unsigned int node)
  1533. {
  1534. while (node && node < D->nnode) {
  1535. if (D->nodes[node].type == BR_NODE_ELEM &&
  1536. D->nodes[node].tag == BR_TAG_FORM)
  1537. return node;
  1538. node = D->nodes[node].parent;
  1539. }
  1540. return 0;
  1541. }
  1542. static void push_form_elements(js_State *state, unsigned int form)
  1543. {
  1544. unsigned int out[128];
  1545. int n = 0, i;
  1546. if (host.form_elements)
  1547. n = host.form_elements(form, out, (int)(sizeof(out) /
  1548. sizeof(out[0])));
  1549. js_newarray(state);
  1550. for (i = 0; i < n; i++) {
  1551. const char *name;
  1552. push_node(state, out[i] + 1);
  1553. js_setindex(state, -2, i);
  1554. name = br_find_attr(D, out[i], "name");
  1555. if (name && name[0]) {
  1556. push_node(state, out[i] + 1);
  1557. js_setproperty(state, -2, name);
  1558. }
  1559. }
  1560. }
  1561. static void form_submit_js(js_State *state)
  1562. {
  1563. unsigned int node = node_of(js_currentfunctiondata(state));
  1564. if (host.form_submit)
  1565. host.form_submit(node);
  1566. }
  1567. static void form_reset_js(js_State *state)
  1568. {
  1569. unsigned int node = node_of(js_currentfunctiondata(state));
  1570. if (host.form_reset)
  1571. host.form_reset(node);
  1572. }
  1573. /* Userdata property hooks: every element wrapper carries node + 1. */
  1574. static int node_has(js_State *state, void *p, const char *name)
  1575. {
  1576. unsigned int node = node_of(p);
  1577. struct br_node *n;
  1578. char buf[64];
  1579. if (!D || node >= D->nnode)
  1580. return 0;
  1581. n = &D->nodes[node];
  1582. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM) {
  1583. if (!strcmp(name, "elements")) {
  1584. push_form_elements(state, node);
  1585. return 1;
  1586. }
  1587. if (!strcmp(name, "length")) {
  1588. unsigned int out[128];
  1589. int count = 0;
  1590. if (host.form_elements)
  1591. count = host.form_elements(node, out,
  1592. (int)(sizeof(out) / sizeof(out[0])));
  1593. js_pushnumber(state, count);
  1594. return 1;
  1595. }
  1596. if (!strcmp(name, "submit")) {
  1597. push_func_data(state, "submit", form_submit_js, 0,
  1598. node + 1);
  1599. return 1;
  1600. }
  1601. if (!strcmp(name, "reset")) {
  1602. push_func_data(state, "reset", form_reset_js, 0,
  1603. node + 1);
  1604. return 1;
  1605. }
  1606. }
  1607. if (!strcmp(name, "form")) {
  1608. unsigned int f;
  1609. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM)
  1610. f = 0;
  1611. else
  1612. f = node_form_ancestor(node);
  1613. if (f)
  1614. push_node(state, f + 1);
  1615. else
  1616. js_pushnull(state);
  1617. return 1;
  1618. }
  1619. if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
  1620. node_push_text(state, node);
  1621. return 1;
  1622. }
  1623. if (!strcmp(name, "nodeValue")) {
  1624. if (n->type == BR_NODE_TEXT || n->type == BR_NODE_COMMENT)
  1625. js_pushlstring(state, D->text + n->text_off,
  1626. (int)n->text_len);
  1627. else
  1628. js_pushnull(state);
  1629. return 1;
  1630. }
  1631. if (!strcmp(name, "nodeType")) {
  1632. js_pushnumber(state, node_type_value(node));
  1633. return 1;
  1634. }
  1635. if (!strcmp(name, "nodeName") || !strcmp(name, "tagName")) {
  1636. node_name(node, buf, sizeof(buf));
  1637. js_pushstring(state, buf);
  1638. return 1;
  1639. }
  1640. if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) {
  1641. unsigned int p = n->parent;
  1642. push_node(state, p ? p + 1 : 0);
  1643. return 1;
  1644. }
  1645. if (!strcmp(name, "childNodes")) {
  1646. push_child_list(state, node, 0);
  1647. return 1;
  1648. }
  1649. if (!strcmp(name, "children")) {
  1650. push_child_list(state, node, 1);
  1651. return 1;
  1652. }
  1653. if (!strcmp(name, "firstChild")) {
  1654. push_node(state, n->first ? n->first + 1 : 0);
  1655. return 1;
  1656. }
  1657. if (!strcmp(name, "lastChild")) {
  1658. push_node(state, n->last ? n->last + 1 : 0);
  1659. return 1;
  1660. }
  1661. if (!strcmp(name, "firstElementChild") ||
  1662. !strcmp(name, "lastElementChild")) {
  1663. unsigned int c = n->first;
  1664. unsigned int found = 0;
  1665. if (!strcmp(name, "lastElementChild")) {
  1666. for (c = n->first; c; c = D->nodes[c].next)
  1667. if (D->nodes[c].type == BR_NODE_ELEM)
  1668. found = c;
  1669. } else {
  1670. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1671. c = D->nodes[c].next;
  1672. found = c;
  1673. }
  1674. push_node(state, found ? found + 1 : 0);
  1675. return 1;
  1676. }
  1677. if (!strcmp(name, "nextSibling") || !strcmp(name, "nextElementSibling")) {
  1678. unsigned int c = n->next;
  1679. if (!strcmp(name, "nextElementSibling"))
  1680. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1681. c = D->nodes[c].next;
  1682. push_node(state, c ? c + 1 : 0);
  1683. return 1;
  1684. }
  1685. if (!strcmp(name, "previousSibling") ||
  1686. !strcmp(name, "previousElementSibling")) {
  1687. unsigned int c = node_prev_sibling(node);
  1688. if (!strcmp(name, "previousElementSibling"))
  1689. while (c && D->nodes[c].type != BR_NODE_ELEM)
  1690. c = node_prev_sibling(c);
  1691. push_node(state, c ? c + 1 : 0);
  1692. return 1;
  1693. }
  1694. if (!strcmp(name, "childElementCount")) {
  1695. unsigned int c, count = 0;
  1696. for (c = n->first; c; c = D->nodes[c].next)
  1697. if (D->nodes[c].type == BR_NODE_ELEM)
  1698. count++;
  1699. js_pushnumber(state, count);
  1700. return 1;
  1701. }
  1702. if (n->tag == BR_TAG_A || n->tag == BR_TAG_AREA) {
  1703. if (!strcmp(name, "href") || !strcmp(name, "protocol") ||
  1704. !strcmp(name, "host") || !strcmp(name, "hostname") ||
  1705. !strcmp(name, "port") || !strcmp(name, "pathname") ||
  1706. !strcmp(name, "search") || !strcmp(name, "hash") ||
  1707. !strcmp(name, "origin")) {
  1708. push_element_url(state, node, name);
  1709. return 1;
  1710. }
  1711. }
  1712. if (!strcmp(name, "id")) { push_attr(state, node, "id", 0); return 1; }
  1713. if (!strcmp(name, "className")) {
  1714. push_attr(state, node, "class", 0);
  1715. return 1;
  1716. }
  1717. if (!strcmp(name, "href")) { push_attr(state, node, "href", 0); return 1; }
  1718. if (!strcmp(name, "src")) { push_attr(state, node, "src", 0); return 1; }
  1719. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_SELECT) {
  1720. if (!strcmp(name, "options")) {
  1721. push_query_array(state, node, "option");
  1722. return 1;
  1723. }
  1724. if (!strcmp(name, "multiple")) {
  1725. js_pushboolean(state, node_attr(node, "multiple") != 0);
  1726. return 1;
  1727. }
  1728. }
  1729. /* An <option> without a value attribute has its text as value. */
  1730. if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_OPTION &&
  1731. !strcmp(name, "value") && !node_attr(node, "value")) {
  1732. node_push_text(state, node);
  1733. return 1;
  1734. }
  1735. if (!strcmp(name, "value")) {
  1736. char buf[128];
  1737. if (host.form_value && host.form_value(node, buf, sizeof(buf)))
  1738. js_pushstring(state, buf);
  1739. else
  1740. push_attr(state, node, "value", 0);
  1741. return 1;
  1742. }
  1743. if (!strcmp(name, "type")) { push_attr(state, node, "type", 0); return 1; }
  1744. if (!strcmp(name, "name")) { push_attr(state, node, "name", 0); return 1; }
  1745. if (!strcmp(name, "alt")) { push_attr(state, node, "alt", 0); return 1; }
  1746. if (!strcmp(name, "title")) { push_attr(state, node, "title", 0); return 1; }
  1747. if (!strcmp(name, "checked")) {
  1748. int c = host.form_checked ? host.form_checked(node) : -1;
  1749. js_pushboolean(state, c >= 0 ? c : node_attr(node, name) != 0);
  1750. return 1;
  1751. }
  1752. if (!strcmp(name, "selectedIndex")) {
  1753. int c = host.form_selected ? host.form_selected(node) : -1;
  1754. js_pushnumber(state, c >= 0 ? c : 0);
  1755. return 1;
  1756. }
  1757. if (!strcmp(name, "selected")) {
  1758. int c = host.form_selected ? host.form_selected(node) : -1;
  1759. if (c >= 0)
  1760. js_pushboolean(state, c != 0);
  1761. else
  1762. js_pushboolean(state, node_attr(node, name) != 0);
  1763. return 1;
  1764. }
  1765. if (!strcmp(name, "disabled")) {
  1766. js_pushboolean(state, node_attr(node, name) != 0);
  1767. return 1;
  1768. }
  1769. if (!strcmp(name, "style")) {
  1770. push_style_object(state, node);
  1771. return 1;
  1772. }
  1773. if (!strcmp(name, "dataset") || !strcmp(name, "domStringMap")) {
  1774. push_dataset(state, node);
  1775. return 1;
  1776. }
  1777. if (!strcmp(name, "classList")) {
  1778. push_classlist(state, node);
  1779. return 1;
  1780. }
  1781. if (!strcmp(name, "attributes")) {
  1782. push_attributes(state, node);
  1783. return 1;
  1784. }
  1785. if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
  1786. char key[32];
  1787. snprintf(key, sizeof(key), "html_%u", node + 1);
  1788. js_getregistry(state, key);
  1789. if (js_isundefined(state, -1)) {
  1790. js_pop(state, 1);
  1791. js_pushstring(state, "");
  1792. }
  1793. return 1;
  1794. }
  1795. if (!strcmp(name, "ownerDocument")) {
  1796. js_getglobal(state, "document");
  1797. return 1;
  1798. }
  1799. if (!strcmp(name, "localName")) {
  1800. unsigned int i;
  1801. if (n->type != BR_NODE_ELEM) {
  1802. js_pushnull(state);
  1803. return 1;
  1804. }
  1805. node_name(node, buf, sizeof(buf));
  1806. for (i = 0; buf[i]; i++)
  1807. if (buf[i] >= 'A' && buf[i] <= 'Z')
  1808. buf[i] = (char)(buf[i] - 'A' + 'a');
  1809. js_pushstring(state, buf);
  1810. return 1;
  1811. }
  1812. if (!strcmp(name, "namespaceURI")) {
  1813. unsigned int a;
  1814. if (n->type != BR_NODE_ELEM) {
  1815. js_pushnull(state);
  1816. return 1;
  1817. }
  1818. for (a = node; a && a < D->nnode; a = D->nodes[a].parent)
  1819. if (D->nodes[a].type == BR_NODE_ELEM &&
  1820. D->nodes[a].tag == BR_TAG_SVG)
  1821. break;
  1822. js_pushstring(state, a && a < D->nnode ?
  1823. "http://www.w3.org/2000/svg" :
  1824. "http://www.w3.org/1999/xhtml");
  1825. return 1;
  1826. }
  1827. if (!strcmp(name, "isConnected")) {
  1828. unsigned int a = node;
  1829. while (a && a < D->nnode && D->nodes[a].parent)
  1830. a = D->nodes[a].parent;
  1831. js_pushboolean(state, a == 0 || a == D->root);
  1832. return 1;
  1833. }
  1834. if (!strcmp(name, "relList")) {
  1835. /* Only supports(): Vite's modulepreload polyfill asks it and
  1836. * otherwise refetches every preloaded module through fetch(). */
  1837. js_newobject(state);
  1838. def_func(state, "supports", rellist_supports, 1);
  1839. return 1;
  1840. }
  1841. if (!strcmp(name, "getAttribute"))
  1842. { push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
  1843. if (!strcmp(name, "setAttribute"))
  1844. { push_func_data(state, "setAttribute", node_setattr, 2, node + 1); return 1; }
  1845. if (!strcmp(name, "removeAttribute"))
  1846. { push_func_data(state, "removeAttribute", node_removeattr, 1, node + 1); return 1; }
  1847. if (!strcmp(name, "hasAttribute"))
  1848. { push_func_data(state, "hasAttribute", node_hasattr, 1, node + 1); return 1; }
  1849. if (!strcmp(name, "appendChild"))
  1850. { push_func_data(state, "appendChild", node_appendchild, 1, node + 1); return 1; }
  1851. if (!strcmp(name, "insertBefore"))
  1852. { push_func_data(state, "insertBefore", node_insertbefore, 2, node + 1); return 1; }
  1853. if (!strcmp(name, "removeChild"))
  1854. { push_func_data(state, "removeChild", node_removechild, 1, node + 1); return 1; }
  1855. if (!strcmp(name, "replaceChild"))
  1856. { push_func_data(state, "replaceChild", node_replacechild, 2, node + 1); return 1; }
  1857. if (!strcmp(name, "cloneNode"))
  1858. { push_func_data(state, "cloneNode", node_clone, 1, node + 1); return 1; }
  1859. if (!strcmp(name, "contains"))
  1860. { push_func_data(state, "contains", node_contains, 1, node + 1); return 1; }
  1861. if (!strcmp(name, "hasChildNodes"))
  1862. { push_func_data(state, "hasChildNodes", node_haschildren, 0, node + 1); return 1; }
  1863. if (!strcmp(name, "remove"))
  1864. { push_func_data(state, "remove", node_remove, 0, node + 1); return 1; }
  1865. if (!strcmp(name, "matches") || !strcmp(name, "webkitMatchesSelector") ||
  1866. !strcmp(name, "mozMatchesSelector") ||
  1867. !strcmp(name, "msMatchesSelector"))
  1868. { push_func_data(state, name, node_matches, 1, node + 1); return 1; }
  1869. if (!strcmp(name, "getElementsByTagName"))
  1870. { push_func_data(state, "getElementsByTagName", node_getelementsbytagname, 1, node + 1); return 1; }
  1871. if (!strcmp(name, "getElementsByClassName"))
  1872. { push_func_data(state, "getElementsByClassName", node_getelementsbyclassname, 1, node + 1); return 1; }
  1873. if (!strcmp(name, "querySelector"))
  1874. { push_func_data(state, "querySelector", node_queryselector, 1, node + 1); return 1; }
  1875. if (!strcmp(name, "querySelectorAll"))
  1876. { push_func_data(state, "querySelectorAll", node_queryselectorall, 1, node + 1); return 1; }
  1877. if (!strcmp(name, "addEventListener"))
  1878. { push_func_data(state, "addEventListener", node_addlistener, 2, node + 1); return 1; }
  1879. if (!strcmp(name, "removeEventListener"))
  1880. { push_func_data(state, "removeEventListener", node_removelistener, 2, node + 1); return 1; }
  1881. if (!strcmp(name, "dispatchEvent"))
  1882. { push_func_data(state, "dispatchEvent", node_dispatchevent, 1, node + 1); return 1; }
  1883. if (!strcmp(name, "getBoundingClientRect"))
  1884. { push_func_data(state, "getBoundingClientRect", node_getrect, 0, node + 1); return 1; }
  1885. if (!strcmp(name, "getClientRects")) {
  1886. js_newarray(state);
  1887. return 1;
  1888. }
  1889. if (!strcmp(name, "offsetWidth") || !strcmp(name, "offsetHeight") ||
  1890. !strcmp(name, "clientWidth") || !strcmp(name, "clientHeight") ||
  1891. !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
  1892. int x = 0, y = 0, w = 0, h = 0;
  1893. if (host.rect)
  1894. host.rect(node, &x, &y, &w, &h);
  1895. js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
  1896. !strcmp(name, "clientHeight") ||
  1897. !strcmp(name, "scrollHeight")) ? h : w);
  1898. return 1;
  1899. }
  1900. if (!strcmp(name, "scrollTop") || !strcmp(name, "scrollLeft")) {
  1901. js_pushnumber(state, 0);
  1902. return 1;
  1903. }
  1904. if (!strcmp(name, "click")) {
  1905. push_func_data(state, "click", node_click, 0, node + 1);
  1906. return 1;
  1907. }
  1908. if (!strcmp(name, "focus") || !strcmp(name, "blur")) {
  1909. push_func_data(state, name, node_noop, 0, node + 1);
  1910. return 1;
  1911. }
  1912. return 0;
  1913. }
  1914. static void node_set_string(unsigned int node, const char *name,
  1915. const char *value)
  1916. {
  1917. br_set_attr(D, node, name, value, (unsigned int)strlen(value));
  1918. if (host.changed)
  1919. host.changed();
  1920. }
  1921. static int node_put(js_State *state, void *p, const char *name)
  1922. {
  1923. unsigned int node = node_of(p);
  1924. if (!D || node >= D->nnode)
  1925. return 0;
  1926. if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
  1927. const char *text = js_tostring(state, -1);
  1928. unsigned int len = (unsigned int)strlen(text);
  1929. if (br_set_text_content(D, node, text, len) != 0) {
  1930. if (host.status)
  1931. host.status("Page text arena is full", 1);
  1932. } else if (host.changed) {
  1933. host.changed();
  1934. }
  1935. return 1;
  1936. }
  1937. if (!strcmp(name, "nodeValue")) {
  1938. const char *text = js_tostring(state, -1);
  1939. if (br_set_text_node(D, node, text,
  1940. (unsigned int)strlen(text)) == 0 &&
  1941. host.changed)
  1942. host.changed();
  1943. return 1;
  1944. }
  1945. if (!strcmp(name, "id") || !strcmp(name, "className") ||
  1946. !strcmp(name, "href") || !strcmp(name, "src") ||
  1947. !strcmp(name, "value") || !strcmp(name, "type") ||
  1948. !strcmp(name, "name") || !strcmp(name, "alt") ||
  1949. !strcmp(name, "title")) {
  1950. const char *value = js_tostring(state, -1);
  1951. if (!strcmp(name, "value") && host.form_set_value &&
  1952. host.form_set_value(node, value))
  1953. return 1;
  1954. if (!strcmp(name, "className"))
  1955. node_set_string(node, "class", value);
  1956. else
  1957. node_set_string(node, name, value);
  1958. return 1;
  1959. }
  1960. if (!strcmp(name, "selectedIndex")) {
  1961. if (host.form_set_selected)
  1962. host.form_set_selected(node, js_tointeger(state, -1));
  1963. return 1;
  1964. }
  1965. if (!strcmp(name, "checked") || !strcmp(name, "disabled") ||
  1966. !strcmp(name, "selected")) {
  1967. int b = js_toboolean(state, -1);
  1968. if (!strcmp(name, "checked") && host.form_set_checked &&
  1969. host.form_set_checked(node, b))
  1970. return 1;
  1971. if (!strcmp(name, "selected") && host.form_set_selected &&
  1972. host.form_set_selected(node, b ? 1 : 0))
  1973. return 1;
  1974. if (b)
  1975. br_set_attr(D, node, name, "", 0);
  1976. else
  1977. br_remove_attr(D, node, name);
  1978. if (host.changed)
  1979. host.changed();
  1980. return 1;
  1981. }
  1982. if (!strcmp(name, "innerHTML")) {
  1983. const char *html = js_tostring(state, -1);
  1984. char key[32];
  1985. br_set_inner_html(D, node, html, (unsigned int)strlen(html));
  1986. snprintf(key, sizeof(key), "html_%u", node + 1);
  1987. js_pushstring(state, html);
  1988. js_setregistry(state, key);
  1989. if (host.changed)
  1990. host.changed();
  1991. return 1;
  1992. }
  1993. if (!strcmp(name, "outerHTML")) {
  1994. char key[32];
  1995. snprintf(key, sizeof(key), "html_%u", node + 1);
  1996. js_pushstring(state, js_tostring(state, -1));
  1997. js_setregistry(state, key);
  1998. return 1;
  1999. }
  2000. if (!strcmp(name, "style")) {
  2001. if (js_isstring(state, -1))
  2002. node_set_string(node, "style",
  2003. js_tostring(state, -1));
  2004. return 1;
  2005. }
  2006. return 0;
  2007. }
  2008. static int node_delete(js_State *state, void *p, const char *name)
  2009. {
  2010. (void)state;
  2011. (void)p;
  2012. (void)name;
  2013. return 0;
  2014. }
  2015. static void doc_getelementbyid(js_State *state)
  2016. {
  2017. const char *id = js_tostring(state, 1);
  2018. push_node(state, br_find_id(D, id));
  2019. }
  2020. static void console_log(js_State *state)
  2021. {
  2022. int i;
  2023. int n = js_gettop(state);
  2024. for (i = 1; i < n; i++) {
  2025. if (i > 1)
  2026. u_putc(' ');
  2027. u_puts(js_tostring(state, i));
  2028. }
  2029. u_putc('\n');
  2030. }
  2031. static void js_alert(js_State *state)
  2032. {
  2033. char msg[160];
  2034. unsigned int used = 0;
  2035. int i;
  2036. int n = js_gettop(state);
  2037. for (i = 1; i < n; i++) {
  2038. const char *s = js_tostring(state, i);
  2039. unsigned int k;
  2040. if (i > 1 && used + 1 < sizeof(msg))
  2041. msg[used++] = ' ';
  2042. for (k = 0; s[k] && used + 1 < sizeof(msg); k++)
  2043. msg[used++] = s[k];
  2044. }
  2045. msg[used] = '\0';
  2046. if (host.status)
  2047. host.status(msg, 0);
  2048. }
  2049. static void push_query_array(js_State *state, unsigned int root,
  2050. const char *selector)
  2051. {
  2052. unsigned int out[256];
  2053. unsigned int n = br_query_all(D, root, selector, out, 256);
  2054. unsigned int i;
  2055. js_newarray(state);
  2056. for (i = 0; i < n; i++) {
  2057. push_node(state, out[i]);
  2058. js_setindex(state, -2, (int)i);
  2059. }
  2060. }
  2061. static void doc_create_element(js_State *state)
  2062. {
  2063. const char *name = js_tostring(state, 1);
  2064. char lower[32];
  2065. unsigned int i;
  2066. for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
  2067. char c = name[i];
  2068. if (c >= 'A' && c <= 'Z')
  2069. c = (char)(c - 'A' + 'a');
  2070. lower[i] = c;
  2071. }
  2072. lower[i] = '\0';
  2073. push_node(state, br_create_element(D, lower, i));
  2074. }
  2075. static void doc_create_text(js_State *state)
  2076. {
  2077. const char *text = js_tostring(state, 1);
  2078. push_node(state, br_create_text(D, text, (unsigned int)strlen(text)));
  2079. }
  2080. static void doc_create_comment(js_State *state)
  2081. {
  2082. const char *text = js_tostring(state, 1);
  2083. push_node(state, br_create_comment(D, text, (unsigned int)strlen(text)));
  2084. }
  2085. static void doc_create_fragment(js_State *state)
  2086. {
  2087. push_node(state, br_create_fragment(D));
  2088. }
  2089. static void doc_create_attribute(js_State *state)
  2090. {
  2091. const char *name = js_tostring(state, 1);
  2092. js_newobject(state);
  2093. js_pushstring(state, name);
  2094. js_setproperty(state, -2, "name");
  2095. js_pushstring(state, "");
  2096. js_setproperty(state, -2, "value");
  2097. js_pushboolean(state, 1);
  2098. js_setproperty(state, -2, "specified");
  2099. }
  2100. static void doc_getelementsbytagname(js_State *state)
  2101. {
  2102. push_query_array(state, 0, js_tostring(state, 1));
  2103. }
  2104. static void doc_getelementsbyclassname(js_State *state)
  2105. {
  2106. const char *name = js_tostring(state, 1);
  2107. char sel[256];
  2108. unsigned int n = 0, i = 0;
  2109. while (name[i] && n + 2 < sizeof(sel)) {
  2110. while (name[i] == ' ')
  2111. i++;
  2112. if (!name[i])
  2113. break;
  2114. sel[n++] = '.';
  2115. while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
  2116. sel[n++] = name[i++];
  2117. }
  2118. sel[n] = '\0';
  2119. push_query_array(state, 0, sel);
  2120. }
  2121. static void doc_queryselector(js_State *state)
  2122. {
  2123. unsigned int out[1];
  2124. unsigned int n = br_query_all(D, 0, js_tostring(state, 1), out, 1);
  2125. if (n)
  2126. push_node(state, out[0]);
  2127. else
  2128. js_pushnull(state);
  2129. }
  2130. static void doc_queryselectorall(js_State *state)
  2131. {
  2132. push_query_array(state, 0, js_tostring(state, 1));
  2133. }
  2134. static void location_get(js_State *state)
  2135. {
  2136. js_pushstring(state, current_url ? current_url : "");
  2137. }
  2138. /* Length of a URL without its #fragment. */
  2139. static unsigned int url_doc_len(const char *u)
  2140. {
  2141. unsigned int n = 0;
  2142. while (u[n] && u[n] != '#')
  2143. n++;
  2144. return n;
  2145. }
  2146. /* Navigate, or, when only the #fragment changes, stay on the page: the
  2147. * host updates the URL (location.href follows it) and a hashchange event is
  2148. * queued. Hash-routed apps (the Cloudron dashboard) navigate this way; a
  2149. * reload would restart the whole app. */
  2150. static void location_go(const char *url)
  2151. {
  2152. char abs[1024];
  2153. unsigned int n;
  2154. if (!current_url || !url) {
  2155. if (host.navigate && url)
  2156. host.navigate(url);
  2157. return;
  2158. }
  2159. url_resolve(current_url, url, abs, sizeof(abs));
  2160. n = url_doc_len(abs);
  2161. if (host.set_hash && abs[n] == '#' && n == url_doc_len(current_url) &&
  2162. !strncmp(abs, current_url, n)) {
  2163. if (strcmp(abs, current_url) && host.set_hash(abs) == 0)
  2164. hash_pending = 1;
  2165. return;
  2166. }
  2167. if (host.navigate)
  2168. host.navigate(url);
  2169. }
  2170. static void location_set(js_State *state)
  2171. {
  2172. location_go(js_tostring(state, 1));
  2173. }
  2174. /* assign()/replace(): navigate (the history entry is not replaced yet). */
  2175. static void location_assign(js_State *state)
  2176. {
  2177. location_go(js_tostring(state, 1));
  2178. js_pushundefined(state);
  2179. }
  2180. static void location_hash_get(js_State *state)
  2181. {
  2182. const char *h = current_url ? strchr(current_url, '#') : 0;
  2183. js_pushstring(state, h && h[1] ? h : "");
  2184. }
  2185. static void location_hash_set(js_State *state)
  2186. {
  2187. const char *v = js_tostring(state, 1);
  2188. char url[1024];
  2189. unsigned int n;
  2190. if (!current_url)
  2191. return;
  2192. n = url_doc_len(current_url);
  2193. if (n + 2 >= sizeof(url))
  2194. return;
  2195. memcpy(url, current_url, n);
  2196. url[n] = '#';
  2197. snprintf(url + n + 1, sizeof(url) - n - 1, "%s", v[0] == '#' ? v + 1 : v);
  2198. location_go(url);
  2199. }
  2200. static void location_reload(js_State *state)
  2201. {
  2202. if (host.navigate && current_url)
  2203. host.navigate(current_url);
  2204. js_pushundefined(state);
  2205. }
  2206. static void location_tostring(js_State *state)
  2207. {
  2208. js_pushstring(state, current_url ? current_url : "");
  2209. }
  2210. static void win_noop(js_State *state);
  2211. struct loc_parts {
  2212. const char *protocol, *host, *hostname, *port, *path, *search, *hash;
  2213. const char *origin;
  2214. unsigned int protocol_len, host_len, hostname_len, port_len;
  2215. unsigned int path_len, search_len, hash_len, origin_len;
  2216. };
  2217. static void loc_split(const char *u, struct loc_parts *p)
  2218. {
  2219. unsigned int n = (unsigned int)strlen(u), i;
  2220. const char *rest;
  2221. memset(p, 0, sizeof(*p));
  2222. p->path = u;
  2223. p->path_len = n;
  2224. p->origin = "null";
  2225. p->origin_len = 4;
  2226. for (i = 0; i < n; i++)
  2227. if (u[i] == ':')
  2228. break;
  2229. if (i + 2 < n && u[i] == ':' && u[i + 1] == '/' && u[i + 2] == '/') {
  2230. const char *hosts = u + i + 3, *hoste = hosts;
  2231. while (*hoste && *hoste != '/' && *hoste != '?' && *hoste != '#')
  2232. hoste++;
  2233. p->protocol = u;
  2234. p->protocol_len = i + 1;
  2235. p->host = hosts;
  2236. p->host_len = (unsigned int)(hoste - hosts);
  2237. p->hostname = hosts;
  2238. p->hostname_len = p->host_len;
  2239. for (i = 0; i < p->hostname_len; i++)
  2240. if (hosts[i] == ':') {
  2241. p->port = hosts + i + 1;
  2242. p->port_len = p->hostname_len - i - 1;
  2243. p->hostname_len = i;
  2244. break;
  2245. }
  2246. p->origin = u;
  2247. p->origin_len = (unsigned int)(hoste - u);
  2248. rest = hoste;
  2249. } else {
  2250. p->protocol = "file:";
  2251. p->protocol_len = 5;
  2252. rest = u;
  2253. }
  2254. {
  2255. const char *q = rest;
  2256. while (*q && *q != '?' && *q != '#')
  2257. q++;
  2258. p->path = rest;
  2259. p->path_len = (unsigned int)(q - rest);
  2260. if (*q == '?') {
  2261. const char *s = q;
  2262. while (*q && *q != '#')
  2263. q++;
  2264. p->search = s;
  2265. p->search_len = (unsigned int)(q - s);
  2266. }
  2267. if (*q == '#') {
  2268. p->hash = q;
  2269. p->hash_len = (unsigned int)strlen(q);
  2270. }
  2271. }
  2272. }
  2273. static void push_location(js_State *state)
  2274. {
  2275. struct loc_parts p;
  2276. loc_split(current_url ? current_url : "", &p);
  2277. js_newobject(state);
  2278. js_newcfunction(state, location_get, "get href", 0);
  2279. js_newcfunction(state, location_set, "set href", 1);
  2280. js_defaccessor(state, -3, "href", 0);
  2281. #define LOC_FIELD(field) \
  2282. do { \
  2283. js_pushlstring(state, p.field ? p.field : "", \
  2284. p.field ? (int)p.field##_len : 0); \
  2285. js_setproperty(state, -2, #field); \
  2286. } while (0)
  2287. LOC_FIELD(protocol);
  2288. LOC_FIELD(host);
  2289. LOC_FIELD(hostname);
  2290. LOC_FIELD(port);
  2291. js_pushlstring(state, p.path ? p.path : "",
  2292. p.path ? (int)p.path_len : 0);
  2293. js_setproperty(state, -2, "pathname");
  2294. LOC_FIELD(search);
  2295. LOC_FIELD(origin);
  2296. #undef LOC_FIELD
  2297. js_newcfunction(state, location_hash_get, "get hash", 0);
  2298. js_newcfunction(state, location_hash_set, "set hash", 1);
  2299. js_defaccessor(state, -3, "hash", 0);
  2300. js_newcfunction(state, location_reload, "reload", 0);
  2301. js_setproperty(state, -2, "reload");
  2302. js_newcfunction(state, location_assign, "assign", 1);
  2303. js_setproperty(state, -2, "assign");
  2304. js_newcfunction(state, location_assign, "replace", 1);
  2305. js_setproperty(state, -2, "replace");
  2306. js_newcfunction(state, location_tostring, "toString", 0);
  2307. js_setproperty(state, -2, "toString");
  2308. }
  2309. /* ---- URL resolution for <a>/<area> URL properties ---- */
  2310. static int url_has_scheme(const char *s)
  2311. {
  2312. unsigned int i = 1;
  2313. if (!((s[0] >= 'a' && s[0] <= 'z') ||
  2314. (s[0] >= 'A' && s[0] <= 'Z')))
  2315. return 0;
  2316. while (s[i]) {
  2317. char c = s[i];
  2318. if (c == ':')
  2319. return 1;
  2320. if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  2321. (c >= '0' && c <= '9') || c == '+' || c == '-' ||
  2322. c == '.'))
  2323. return 0;
  2324. i++;
  2325. }
  2326. return 0;
  2327. }
  2328. static void url_put(char *out, unsigned int cap, unsigned int *n,
  2329. const char *s, unsigned int len)
  2330. {
  2331. unsigned int i;
  2332. for (i = 0; i < len && *n + 1 < cap; i++)
  2333. out[(*n)++] = s[i];
  2334. }
  2335. /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
  2336. static void url_normalize(char *url)
  2337. {
  2338. char tmp[1024];
  2339. char *path;
  2340. unsigned int n = 0, i = 0;
  2341. path = strstr(url, "://");
  2342. if (path) {
  2343. path += 3;
  2344. while (*path && *path != '/')
  2345. path++;
  2346. } else {
  2347. path = url;
  2348. }
  2349. if (path[0] != '/')
  2350. return;
  2351. /* The path only: ?query and #fragment are copied verbatim below. */
  2352. while (path[i] && path[i] != '?' && path[i] != '#') {
  2353. unsigned int start;
  2354. while (path[i] == '/')
  2355. i++;
  2356. start = i;
  2357. while (path[i] && path[i] != '/' && path[i] != '?' &&
  2358. path[i] != '#')
  2359. i++;
  2360. if (i == start)
  2361. continue;
  2362. if (i - start == 1 && path[start] == '.')
  2363. continue;
  2364. if (i - start == 2 && path[start] == '.' &&
  2365. path[start + 1] == '.') {
  2366. while (n > 0 && tmp[n - 1] != '/')
  2367. n--;
  2368. if (n > 0)
  2369. n--;
  2370. continue;
  2371. }
  2372. if (n + 1 < sizeof(tmp))
  2373. tmp[n++] = '/';
  2374. while (start < i && n + 1 < sizeof(tmp))
  2375. tmp[n++] = path[start++];
  2376. }
  2377. if (n == 0)
  2378. tmp[n++] = '/';
  2379. else if (i > 0 && path[i - 1] == '/' && n + 1 < sizeof(tmp))
  2380. tmp[n++] = '/'; /* keep "dir/" a directory */
  2381. while (path[i] && n + 1 < sizeof(tmp))
  2382. tmp[n++] = path[i++];
  2383. tmp[n] = '\0';
  2384. memcpy(path, tmp, n + 1);
  2385. }
  2386. static void url_resolve(const char *base, const char *rel,
  2387. char *out, unsigned int cap)
  2388. {
  2389. struct loc_parts bp;
  2390. unsigned int n = 0, i;
  2391. if (cap == 0)
  2392. return;
  2393. if (!rel[0]) {
  2394. url_put(out, cap, &n, base, (unsigned int)strlen(base));
  2395. out[n] = '\0';
  2396. return;
  2397. }
  2398. if (url_has_scheme(rel)) {
  2399. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2400. out[n] = '\0';
  2401. url_normalize(out);
  2402. return;
  2403. }
  2404. loc_split(base, &bp);
  2405. if (rel[0] == '/' && rel[1] == '/') {
  2406. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2407. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2408. } else if (rel[0] == '/') {
  2409. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2410. url_put(out, cap, &n, "//", 2);
  2411. url_put(out, cap, &n, bp.host, bp.host_len);
  2412. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2413. } else if (rel[0] == '#' || rel[0] == '?') {
  2414. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2415. if (bp.host_len || (bp.protocol_len == 5 &&
  2416. bp.protocol[0] == 'f')) {
  2417. url_put(out, cap, &n, "//", 2);
  2418. url_put(out, cap, &n, bp.host, bp.host_len);
  2419. }
  2420. url_put(out, cap, &n, bp.path, bp.path_len);
  2421. if (rel[0] == '#')
  2422. url_put(out, cap, &n, bp.search, bp.search_len);
  2423. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2424. } else {
  2425. const char *dir_end = bp.path;
  2426. for (i = 0; i < bp.path_len; i++)
  2427. if (bp.path[i] == '/')
  2428. dir_end = bp.path + i + 1;
  2429. if (dir_end == bp.path)
  2430. dir_end = bp.path + bp.path_len;
  2431. url_put(out, cap, &n, bp.protocol, bp.protocol_len);
  2432. if (bp.host_len || (bp.protocol_len == 5 &&
  2433. bp.protocol[0] == 'f')) {
  2434. url_put(out, cap, &n, "//", 2);
  2435. url_put(out, cap, &n, bp.host, bp.host_len);
  2436. }
  2437. url_put(out, cap, &n, bp.path,
  2438. (unsigned int)(dir_end - bp.path));
  2439. url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
  2440. }
  2441. out[n] = '\0';
  2442. url_normalize(out);
  2443. }
  2444. /* <a> URL properties are resolved against the page URL, like the DOM. */
  2445. static void push_element_url(js_State *state, unsigned int node,
  2446. const char *name)
  2447. {
  2448. char abs_url[512];
  2449. const char *href = br_find_attr(D, node, "href");
  2450. struct loc_parts p;
  2451. if (!href || !href[0]) {
  2452. js_pushstring(state, "");
  2453. return;
  2454. }
  2455. url_resolve(current_url ? current_url : "/", href,
  2456. abs_url, sizeof(abs_url));
  2457. loc_split(abs_url, &p);
  2458. if (!strcmp(name, "href"))
  2459. js_pushstring(state, abs_url);
  2460. else if (!strcmp(name, "protocol"))
  2461. js_pushlstring(state, p.protocol, (int)p.protocol_len);
  2462. else if (!strcmp(name, "origin"))
  2463. js_pushlstring(state, p.origin ? p.origin : "",
  2464. (int)p.origin_len);
  2465. else if (!strcmp(name, "host"))
  2466. js_pushlstring(state, p.host ? p.host : "", (int)p.host_len);
  2467. else if (!strcmp(name, "hostname"))
  2468. js_pushlstring(state, p.hostname ? p.hostname : "",
  2469. (int)p.hostname_len);
  2470. else if (!strcmp(name, "port"))
  2471. js_pushlstring(state, p.port ? p.port : "", (int)p.port_len);
  2472. else if (!strcmp(name, "pathname"))
  2473. js_pushlstring(state, p.path ? p.path : "", (int)p.path_len);
  2474. else if (!strcmp(name, "search"))
  2475. js_pushlstring(state, p.search ? p.search : "",
  2476. (int)p.search_len);
  2477. else
  2478. js_pushlstring(state, p.hash ? p.hash : "", (int)p.hash_len);
  2479. }
  2480. static void win_noop(js_State *state)
  2481. {
  2482. (void)state;
  2483. }
  2484. static void timer_add(js_State *state, int repeat)
  2485. {
  2486. int i;
  2487. unsigned int ms;
  2488. if (!js_iscallable(state, 1)) {
  2489. js_pushnumber(state, 0);
  2490. return;
  2491. }
  2492. ms = js_isdefined(state, 2) ?
  2493. (unsigned int)js_tointeger(state, 2) : 0;
  2494. if (repeat && ms == 0)
  2495. ms = 1;
  2496. for (i = 0; i < JS_TIMERS; i++)
  2497. if (!timers[i].used)
  2498. break;
  2499. if (i == JS_TIMERS) {
  2500. js_pushnumber(state, 0);
  2501. return;
  2502. }
  2503. js_copy(state, 1);
  2504. snprintf(timers[i].ref, sizeof(timers[i].ref), "%s",
  2505. js_ref(state));
  2506. timers[i].used = 1;
  2507. timers[i].repeat = repeat;
  2508. timers[i].interval = ms;
  2509. timers[i].deadline = u_ticks_ms() + ms;
  2510. js_pushnumber(state, i + 1);
  2511. }
  2512. static void win_settimeout(js_State *state)
  2513. {
  2514. timer_add(state, 0);
  2515. }
  2516. static void win_setinterval(js_State *state)
  2517. {
  2518. timer_add(state, 1);
  2519. }
  2520. static void timer_clear(js_State *state)
  2521. {
  2522. int id = js_tointeger(state, 1);
  2523. if (id >= 1 && id <= JS_TIMERS && timers[id - 1].used) {
  2524. js_unref(state, timers[id - 1].ref);
  2525. timers[id - 1].used = 0;
  2526. }
  2527. }
  2528. static void win_requestanimationframe(js_State *state)
  2529. {
  2530. timer_add(state, 0);
  2531. }
  2532. static void win_performance_now(js_State *state)
  2533. {
  2534. js_pushnumber(state, (double)u_ticks_ms());
  2535. }
  2536. struct computed_prop {
  2537. const char *js;
  2538. const char *css;
  2539. };
  2540. static const struct computed_prop computed_props[] = {
  2541. { "display", "display" }, { "position", "position" },
  2542. { "width", "width" }, { "height", "height" },
  2543. { "color", "color" }, { "backgroundColor", "background-color" },
  2544. { "fill", "fill" }, { "stroke", "stroke" },
  2545. { "fontSize", "font-size" }, { "fontWeight", "font-weight" },
  2546. { "fontStyle", "font-style" }, { "fontFamily", "font-family" },
  2547. { "textAlign", "text-align" }, { "float", "float" },
  2548. { "cssFloat", "float" }, { "clear", "clear" },
  2549. { "opacity", "opacity" }, { "visibility", "visibility" },
  2550. { "overflow", "overflow" }, { "whiteSpace", "white-space" },
  2551. { "textTransform", "text-transform" }, { "boxSizing", "box-sizing" },
  2552. { "lineHeight", "line-height" }, { "zIndex", "z-index" },
  2553. { "top", "top" }, { "left", "left" }, { "right", "right" },
  2554. { "bottom", "bottom" },
  2555. { "marginTop", "margin-top" }, { "marginRight", "margin-right" },
  2556. { "marginBottom", "margin-bottom" }, { "marginLeft", "margin-left" },
  2557. { "paddingTop", "padding-top" }, { "paddingRight", "padding-right" },
  2558. { "paddingBottom", "padding-bottom" },
  2559. { "paddingLeft", "padding-left" },
  2560. { "borderTopWidth", "border-top-width" },
  2561. { "borderRightWidth", "border-right-width" },
  2562. { "borderBottomWidth", "border-bottom-width" },
  2563. { "borderLeftWidth", "border-left-width" },
  2564. { "borderTopColor", "border-top-color" },
  2565. { "borderRightColor", "border-right-color" },
  2566. { "borderBottomColor", "border-bottom-color" },
  2567. { "borderLeftColor", "border-left-color" },
  2568. { "backgroundImage", "background-image" },
  2569. { "backgroundRepeat", "background-repeat" },
  2570. { "backgroundPosition", "background-position" },
  2571. { "backgroundSize", "background-size" },
  2572. { "transform", "transform" },
  2573. { 0, 0 }
  2574. };
  2575. static void computed_get(js_State *state)
  2576. {
  2577. unsigned int node = node_of(js_currentfunctiondata(state));
  2578. const char *prop = js_tostring(state, 1);
  2579. char buf[192];
  2580. if (host.computed && host.computed(node, prop, buf, sizeof(buf)))
  2581. js_pushstring(state, buf);
  2582. else
  2583. js_pushstring(state, "");
  2584. }
  2585. static void win_getcomputedstyle(js_State *state)
  2586. {
  2587. unsigned int node = 0;
  2588. char buf[192];
  2589. int i;
  2590. if (js_isuserdata(state, 1, "node"))
  2591. node = node_of(js_touserdata(state, 1, "node"));
  2592. js_newobject(state);
  2593. def_func_data(state, "getPropertyValue", computed_get, 1, node + 1);
  2594. for (i = 0; computed_props[i].js; i++) {
  2595. if (!host.computed ||
  2596. !host.computed(node, computed_props[i].css, buf,
  2597. sizeof(buf)))
  2598. continue;
  2599. js_pushstring(state, buf);
  2600. js_setproperty(state, -2, computed_props[i].js);
  2601. }
  2602. js_pushstring(state, "");
  2603. js_setproperty(state, -2, "cssText");
  2604. }
  2605. static void win_matchmedia(js_State *state)
  2606. {
  2607. const char *query = js_tostring(state, 1);
  2608. js_newobject(state);
  2609. js_pushboolean(state, 0);
  2610. js_setproperty(state, -2, "matches");
  2611. js_pushstring(state, query);
  2612. js_setproperty(state, -2, "media");
  2613. def_func(state, "addListener", win_noop, 1);
  2614. def_func(state, "removeListener", win_noop, 1);
  2615. def_func(state, "addEventListener", win_noop, 2);
  2616. def_func(state, "removeEventListener", win_noop, 2);
  2617. }
  2618. static void rellist_supports(js_State *state)
  2619. {
  2620. const char *t = js_tostring(state, 1);
  2621. js_pushboolean(state, !strcmp(t, "modulepreload") ||
  2622. !strcmp(t, "preload") || !strcmp(t, "stylesheet"));
  2623. }
  2624. /* ---- primitives for js_prelude.js ---- */
  2625. /* __nb_http(method, url, contentType, body) -> [status, ctype, url, text].
  2626. * Synchronous: the host fetches through its helpers while the script
  2627. * waits. A network failure throws (fetch() turns it into a TypeError). */
  2628. static void nb_http(js_State *state)
  2629. {
  2630. struct js_http_resp r;
  2631. const char *method = js_tostring(state, 1);
  2632. const char *url = js_tostring(state, 2);
  2633. const char *ctype = js_tostring(state, 3);
  2634. const char *body = js_tostring(state, 4);
  2635. char err[96];
  2636. int rv;
  2637. memset(&r, 0, sizeof(r));
  2638. err[0] = '\0';
  2639. rv = host.http ? host.http(method, url, ctype, body,
  2640. (unsigned int)strlen(body), &r, err,
  2641. (int)sizeof(err)) : -1;
  2642. /* The budget covers running JavaScript, not the network wait. */
  2643. js_setlimit(state, JS_RUN_LIMIT, 0);
  2644. if (rv != 0) {
  2645. free(r.body);
  2646. js_typeerror(state, "network error: %s",
  2647. err[0] ? err : "fetch failed");
  2648. }
  2649. js_newarray(state);
  2650. js_pushnumber(state, r.status);
  2651. js_setindex(state, -2, 0);
  2652. js_pushstring(state, r.ctype);
  2653. js_setindex(state, -2, 1);
  2654. js_pushstring(state, r.url);
  2655. js_setindex(state, -2, 2);
  2656. js_pushlstring(state, r.body ? r.body : "", (int)r.len);
  2657. js_setindex(state, -2, 3);
  2658. free(r.body);
  2659. }
  2660. #define JS_STORAGE_MAX (32u * 1024u)
  2661. /* __nb_storage(kind) -> text, __nb_storage(kind, text) stores it. */
  2662. static void nb_storage(js_State *state)
  2663. {
  2664. int kind = js_tointeger(state, 1);
  2665. char *buf;
  2666. int n;
  2667. if (js_isstring(state, 2)) {
  2668. if (host.storage)
  2669. host.storage(kind, js_tostring(state, 2), 0, 0);
  2670. js_pushundefined(state);
  2671. return;
  2672. }
  2673. buf = (char *)malloc(JS_STORAGE_MAX);
  2674. n = buf && host.storage ?
  2675. host.storage(kind, 0, buf, (int)JS_STORAGE_MAX) : -1;
  2676. if (n > 0)
  2677. js_pushlstring(state, buf, n);
  2678. else
  2679. js_pushstring(state, "");
  2680. free(buf);
  2681. }
  2682. static void url_resolve(const char *base, const char *rel,
  2683. char *out, unsigned int cap);
  2684. static void nb_resolve(js_State *state)
  2685. {
  2686. char out[512];
  2687. url_resolve(js_tostring(state, 1), js_tostring(state, 2), out,
  2688. sizeof(out));
  2689. js_pushstring(state, out);
  2690. }
  2691. extern const char js_prelude_source[];
  2692. static void install_prelude(js_State *state)
  2693. {
  2694. js_newcfunction(state, nb_http, "__nb_http", 4);
  2695. js_defglobal(state, "__nb_http", 0);
  2696. js_newcfunction(state, nb_storage, "__nb_storage", 2);
  2697. js_defglobal(state, "__nb_storage", 0);
  2698. js_newcfunction(state, nb_resolve, "__nb_resolve", 2);
  2699. js_defglobal(state, "__nb_resolve", 0);
  2700. js_getregistry(state, "nodeproto");
  2701. js_defglobal(state, "__nb_nodeproto", 0);
  2702. if (js_ploadstring(state, "[prelude]", js_prelude_source)) {
  2703. report_top(state);
  2704. return;
  2705. }
  2706. js_pushundefined(state);
  2707. if (js_pcall(state, 0))
  2708. report_top(state);
  2709. else
  2710. js_pop(state, 1);
  2711. }
  2712. static void install_globals(js_State *state)
  2713. {
  2714. unsigned int h;
  2715. /* Shared prototype of the node/style/dataset wrappers. */
  2716. js_newobject(state);
  2717. js_setregistry(state, "wrapproto");
  2718. /* DOM node wrappers: their own prototype, so the prelude can add the
  2719. * Element methods there without touching style/dataset objects. */
  2720. js_newobject(state);
  2721. js_setregistry(state, "nodeproto");
  2722. js_newobject(state);
  2723. def_func(state, "getElementById", doc_getelementbyid, 1);
  2724. def_func(state, "createElement", doc_create_element, 1);
  2725. def_func(state, "createTextNode", doc_create_text, 1);
  2726. def_func(state, "createComment", doc_create_comment, 1);
  2727. def_func(state, "createDocumentFragment", doc_create_fragment, 0);
  2728. def_func(state, "createAttribute", doc_create_attribute, 1);
  2729. def_func(state, "getElementsByTagName", doc_getelementsbytagname, 1);
  2730. def_func(state, "getElementsByClassName", doc_getelementsbyclassname, 1);
  2731. def_func(state, "querySelector", doc_queryselector, 1);
  2732. def_func(state, "querySelectorAll", doc_queryselectorall, 1);
  2733. def_func(state, "addEventListener", doc_addlistener, 2);
  2734. def_func(state, "removeEventListener", doc_removelistener, 2);
  2735. def_func(state, "createEvent", doc_createevent, 1);
  2736. h = br_find_tag(D, BR_TAG_HTML);
  2737. if (!h && D->nnode > 1)
  2738. h = D->nodes[0].first ? D->nodes[0].first + 1 : 0;
  2739. push_node(state, h);
  2740. js_setproperty(state, -2, "documentElement");
  2741. h = br_find_tag(D, BR_TAG_BODY);
  2742. push_node(state, h);
  2743. js_setproperty(state, -2, "body");
  2744. h = br_find_tag(D, BR_TAG_HEAD);
  2745. push_node(state, h);
  2746. js_setproperty(state, -2, "head");
  2747. js_pushnumber(state, 9);
  2748. js_setproperty(state, -2, "nodeType");
  2749. js_pushstring(state, "#document");
  2750. js_setproperty(state, -2, "nodeName");
  2751. js_pushnull(state);
  2752. js_setproperty(state, -2, "ownerDocument");
  2753. js_pushstring(state, "CSS1Compat");
  2754. js_setproperty(state, -2, "compatMode");
  2755. js_pushstring(state, D->title);
  2756. js_setproperty(state, -2, "title");
  2757. js_pushstring(state, "complete");
  2758. js_setproperty(state, -2, "readyState");
  2759. js_pushstring(state, "");
  2760. js_setproperty(state, -2, "cookie");
  2761. js_pushstring(state, current_url ? current_url : "");
  2762. js_setproperty(state, -2, "URL");
  2763. js_defglobal(state, "document", JS_DONTENUM);
  2764. js_newobject(state);
  2765. js_newcfunction(state, console_log, "log", 0);
  2766. js_setproperty(state, -2, "log");
  2767. js_defglobal(state, "console", JS_DONTENUM);
  2768. js_newcfunction(state, js_alert, "alert", 1);
  2769. js_defglobal(state, "alert", JS_DONTENUM);
  2770. js_newcfunction(state, event_call, "Event", 1);
  2771. js_defglobal(state, "Event", JS_DONTENUM);
  2772. js_newcfunction(state, custom_event_call, "CustomEvent", 1);
  2773. js_defglobal(state, "CustomEvent", JS_DONTENUM);
  2774. js_newcfunction(state, mouse_event_call, "MouseEvent", 1);
  2775. js_defglobal(state, "MouseEvent", JS_DONTENUM);
  2776. push_location(state);
  2777. js_defglobal(state, "location", JS_DONTENUM);
  2778. js_newobject(state);
  2779. js_pushstring(state, "Mozilla/5.0 (X11; Linux i686) NebOS/0.2");
  2780. js_setproperty(state, -2, "userAgent");
  2781. js_pushstring(state, "NebOS");
  2782. js_setproperty(state, -2, "platform");
  2783. js_pushstring(state, "en-US");
  2784. js_setproperty(state, -2, "language");
  2785. js_defglobal(state, "navigator", JS_DONTENUM);
  2786. js_newobject(state);
  2787. js_pushnumber(state, 1);
  2788. js_setproperty(state, -2, "length");
  2789. def_func(state, "pushState", win_noop, 3);
  2790. def_func(state, "replaceState", win_noop, 3);
  2791. def_func(state, "back", win_noop, 0);
  2792. def_func(state, "forward", win_noop, 0);
  2793. def_func(state, "go", win_noop, 1);
  2794. js_defglobal(state, "history", JS_DONTENUM);
  2795. def_global_func(state, "matchMedia", win_matchmedia, 1);
  2796. def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
  2797. def_global_func(state, "addEventListener", win_addlistener, 2);
  2798. def_global_func(state, "removeEventListener", win_removelistener, 2);
  2799. def_global_func(state, "scrollTo", win_noop, 2);
  2800. def_global_func(state, "scrollBy", win_noop, 2);
  2801. def_global_func(state, "setTimeout", win_settimeout, 1);
  2802. def_global_func(state, "setInterval", win_setinterval, 1);
  2803. def_global_func(state, "clearTimeout", timer_clear, 1);
  2804. def_global_func(state, "clearInterval", timer_clear, 1);
  2805. def_global_func(state, "requestAnimationFrame", win_requestanimationframe, 1);
  2806. def_global_func(state, "cancelAnimationFrame", timer_clear, 1);
  2807. js_newobject(state);
  2808. def_func(state, "now", win_performance_now, 0);
  2809. js_newobject(state);
  2810. js_setproperty(state, -2, "timing");
  2811. js_defglobal(state, "performance", JS_DONTENUM);
  2812. js_pushnumber(state, host.width ? (int)host.width : 1024);
  2813. js_defglobal(state, "innerWidth", JS_DONTENUM);
  2814. js_pushnumber(state, host.height ? (int)host.height : 768);
  2815. js_defglobal(state, "innerHeight", JS_DONTENUM);
  2816. js_pushnumber(state, 0);
  2817. js_defglobal(state, "pageXOffset", JS_DONTENUM);
  2818. js_pushnumber(state, 0);
  2819. js_defglobal(state, "pageYOffset", JS_DONTENUM);
  2820. js_pushnumber(state, 0);
  2821. js_defglobal(state, "scrollX", JS_DONTENUM);
  2822. js_pushnumber(state, 0);
  2823. js_defglobal(state, "scrollY", JS_DONTENUM);
  2824. js_pushnumber(state, 1);
  2825. js_defglobal(state, "devicePixelRatio", JS_DONTENUM);
  2826. js_pushglobal(state);
  2827. js_defglobal(state, "window", JS_DONTENUM);
  2828. js_pushglobal(state);
  2829. js_defglobal(state, "globalThis", JS_DONTENUM);
  2830. js_getglobal(state, "document");
  2831. js_getglobal(state, "location");
  2832. js_setproperty(state, -2, "location");
  2833. js_pop(state, 1);
  2834. js_getglobal(state, "document");
  2835. js_pushglobal(state);
  2836. js_setproperty(state, -2, "defaultView");
  2837. js_pop(state, 1);
  2838. }
  2839. static int module_resolve(const char *base, const char *name, char *out,
  2840. unsigned int cap)
  2841. {
  2842. url_resolve(base && base[0] ? base :
  2843. (current_url ? current_url : ""), name, out, cap);
  2844. return 0;
  2845. }
  2846. static char *module_load(const char *url, unsigned int *len)
  2847. {
  2848. char *src;
  2849. if (!host.load_script)
  2850. return 0;
  2851. src = host.load_script(url, len);
  2852. if (J)
  2853. js_setlimit(J, JS_RUN_LIMIT, 0);
  2854. if (!src && host.report) {
  2855. char msg[600];
  2856. snprintf(msg, sizeof(msg), "Cannot load module %s", url);
  2857. host.report(msg);
  2858. }
  2859. return src;
  2860. }
  2861. int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
  2862. {
  2863. if (!doc || !h)
  2864. return -1;
  2865. D = doc;
  2866. host = *h;
  2867. current_url = h->page_url;
  2868. panic_armed = 0;
  2869. memset(timers, 0, sizeof(timers));
  2870. memset(listeners, 0, sizeof(listeners));
  2871. memset(events, 0, sizeof(events));
  2872. memset(event_templates, 0, sizeof(event_templates));
  2873. /* Classic scripts are sloppy by default in browsers; strict mode is
  2874. * opt-in via a "use strict" directive. */
  2875. J = js_newstate(0, 0, 0);
  2876. if (!J)
  2877. return -1;
  2878. js_setreport(J, report_cb);
  2879. js_atpanic(J, panic_cb);
  2880. js_setmodulehost(J, module_resolve, module_load);
  2881. install_globals(J);
  2882. js_setlimit(J, JS_RUN_LIMIT, 0);
  2883. install_prelude(J);
  2884. return 0;
  2885. }
  2886. void js_browser_stop(void)
  2887. {
  2888. if (J)
  2889. js_freestate(J);
  2890. J = 0;
  2891. D = 0;
  2892. current_url = 0;
  2893. panic_armed = 0;
  2894. memset(timers, 0, sizeof(timers));
  2895. }
  2896. int js_browser_active(void)
  2897. {
  2898. return J != 0;
  2899. }
  2900. static void report_top(js_State *state)
  2901. {
  2902. const char *msg;
  2903. /* An "interrupted" error leaves the deadline expired: formatting the
  2904. * error runs JavaScript (toString), which would be interrupted too. */
  2905. js_setlimit(state, 0, 0);
  2906. js_getproperty(state, -1, "stack");
  2907. if (js_isstring(state, -1)) {
  2908. /* QuickJS's stack is only the frames: lead with
  2909. * "Name: message" like the MuJS reports did. */
  2910. char buf[768];
  2911. const char *head = js_trystring(state, -2, "JavaScript error");
  2912. snprintf(buf, sizeof(buf), "%s\n%s", head,
  2913. js_tostring(state, -1));
  2914. msg = buf;
  2915. if (host.report)
  2916. host.report(msg);
  2917. js_pop(state, 1);
  2918. } else {
  2919. js_pop(state, 1);
  2920. msg = js_trystring(state, -1, "JavaScript error");
  2921. if (host.report)
  2922. host.report(msg);
  2923. }
  2924. js_pop(state, 1);
  2925. }
  2926. void js_browser_hashchange(void)
  2927. {
  2928. hash_pending = 1;
  2929. }
  2930. void js_browser_tick(void)
  2931. {
  2932. unsigned int now;
  2933. int i, ran = 0;
  2934. if (!J)
  2935. return;
  2936. if (hash_pending) {
  2937. hash_pending = 0;
  2938. js_browser_event(JS_TARGET_WINDOW, "hashchange", 0, 0);
  2939. if (!J)
  2940. return;
  2941. }
  2942. now = u_ticks_ms();
  2943. for (i = 0; i < JS_TIMERS; i++) {
  2944. if (!timers[i].used ||
  2945. (int)(now - timers[i].deadline) < 0)
  2946. continue;
  2947. js_setlimit(J, JS_RUN_LIMIT, 0);
  2948. js_getregistry(J, timers[i].ref);
  2949. if (!js_iscallable(J, -1)) {
  2950. js_pop(J, 1);
  2951. js_unref(J, timers[i].ref);
  2952. timers[i].used = 0;
  2953. continue;
  2954. }
  2955. js_pushundefined(J);
  2956. if (js_pcall(J, 0))
  2957. report_top(J);
  2958. else
  2959. js_pop(J, 1);
  2960. if (timers[i].used) {
  2961. if (timers[i].repeat)
  2962. timers[i].deadline = now + timers[i].interval;
  2963. else {
  2964. js_unref(J, timers[i].ref);
  2965. timers[i].used = 0;
  2966. }
  2967. }
  2968. if (++ran >= 4)
  2969. break;
  2970. }
  2971. js_runjobs(J);
  2972. }
  2973. int js_browser_run(const char *source, const char *url)
  2974. {
  2975. int r;
  2976. if (!J || !D)
  2977. return -1;
  2978. js_setlimit(J, JS_RUN_LIMIT, 0);
  2979. panic_armed = 1;
  2980. if (setjmp(panic_env)) {
  2981. panic_armed = 0;
  2982. if (host.report)
  2983. host.report("uncaught JavaScript exception");
  2984. /* The try/exception stack is unusable after a panic. Leak the
  2985. * state; the page heap reset on navigation reclaims it. */
  2986. J = 0;
  2987. D = 0;
  2988. return -1;
  2989. }
  2990. if (js_ploadstring(J, url ? url : "[inline]", source)) {
  2991. report_top(J);
  2992. panic_armed = 0;
  2993. return -1;
  2994. }
  2995. js_pushundefined(J);
  2996. r = js_pcall(J, 0);
  2997. if (r) {
  2998. report_top(J);
  2999. panic_armed = 0;
  3000. return -1;
  3001. }
  3002. js_pop(J, 1);
  3003. js_runjobs(J);
  3004. panic_armed = 0;
  3005. return 0;
  3006. }
  3007. /* Run a <script type="module">: imports are resolved against `url` and
  3008. * loaded through host.load_script. */
  3009. int js_browser_run_module(const char *source, const char *url)
  3010. {
  3011. if (!J || !D)
  3012. return -1;
  3013. js_setlimit(J, JS_RUN_LIMIT, 0);
  3014. panic_armed = 1;
  3015. if (setjmp(panic_env)) {
  3016. panic_armed = 0;
  3017. if (host.report)
  3018. host.report("uncaught JavaScript exception");
  3019. J = 0;
  3020. D = 0;
  3021. return -1;
  3022. }
  3023. if (js_ploadmodule(J, url ? url : "[module]", source)) {
  3024. report_top(J);
  3025. panic_armed = 0;
  3026. return -1;
  3027. }
  3028. js_pop(J, 1);
  3029. panic_armed = 0;
  3030. return 0;
  3031. }