js_browser.c 77 KB

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