js_browser.c 86 KB

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