js_browser.c 83 KB

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