js_browser.c 96 KB

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