js_browser.c 77 KB

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