| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057 |
- /* Browser bindings for the page JavaScript engine (QuickJS, driven through
- * the MuJS-style stack API in js_mu.c): the DOM layer (interned node wrappers,
- * attributes, query selectors, classList/dataset/style, innerHTML, timers)
- * plus document/window/location/navigator globals. */
- #include <setjmp.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "ucmd_lib.h"
- #include "browser_html.h"
- #include "js_browser.h"
- #include "js_mu.h"
- /* Wall-clock budget per script/handler/timer entry, in milliseconds. It is
- * reset before every entry; a runaway loop becomes a catchable
- * "interrupted" exception instead of a frozen browser. */
- #define JS_RUN_LIMIT 10000
- #define JS_TIMERS 16
- struct js_timer {
- int used;
- int repeat;
- unsigned int deadline;
- unsigned int interval;
- char ref[32];
- };
- static struct js_timer timers[JS_TIMERS];
- static js_State *J;
- static struct br_doc *D;
- static struct js_browser_host host;
- static const char *current_url;
- static jmp_buf panic_env;
- static int panic_armed;
- static void report_top(js_State *state);
- static void report_cb(js_State *state, const char *message)
- {
- (void)state;
- if (host.report)
- host.report(message);
- }
- static void panic_cb(js_State *state)
- {
- if (panic_armed)
- longjmp(panic_env, 1);
- if (js_isobject(state, -1))
- report_top(state);
- else if (host.report)
- host.report(js_trystring(state, -1,
- "uncaught JavaScript exception"));
- if (host.report)
- host.report("uncaught JavaScript exception");
- }
- static unsigned int node_of(void *p)
- {
- return (unsigned int)(uintptr_t)p - 1;
- }
- static int node_has(js_State *state, void *p, const char *name);
- static int node_put(js_State *state, void *p, const char *name);
- static int node_delete(js_State *state, void *p, const char *name);
- static void push_element_url(js_State *state, unsigned int node,
- const char *name);
- /* One wrapper per DOM node: the same element must have the same object
- * identity on every access, or library caches (jQuery expando data, Sizzle)
- * silently split into disconnected copies. */
- static void push_node(js_State *state, unsigned int handle)
- {
- char key[24];
- if (!handle) {
- js_pushnull(state);
- return;
- }
- snprintf(key, sizeof(key), "jsonnode_%u", handle);
- js_getregistry(state, key);
- if (!js_isundefined(state, -1))
- return;
- js_pop(state, 1);
- /* js_newuserdatax() pops a prototype from the top. Wrappers inherit
- * from Object.prototype like real DOM nodes (toString/hasOwnProperty;
- * Angular calls node.toString() to sniff SVG). */
- js_getregistry(state, "wrapproto");
- js_newuserdatax(state, "node", (void *)(uintptr_t)handle,
- node_has, node_put, node_delete, 0);
- js_copy(state, -1);
- js_setregistry(state, key);
- }
- static unsigned int arg_node(js_State *state, int idx)
- {
- if (!js_isuserdata(state, idx, "node"))
- js_typeerror(state, "not a DOM node");
- return (unsigned int)(uintptr_t)js_touserdata(state, idx, "node");
- }
- static void def_func_data(js_State *state, const char *name,
- js_CFunction fn, int length, unsigned int handle)
- {
- js_newcfunctionx(state, fn, name, length,
- (void *)(uintptr_t)handle, 0);
- js_setproperty(state, -2, name);
- }
- static void def_func(js_State *state, const char *name,
- js_CFunction fn, int length)
- {
- js_newcfunction(state, fn, name, length);
- js_setproperty(state, -2, name);
- }
- static void def_global_func(js_State *state, const char *name,
- js_CFunction fn, int length)
- {
- js_newcfunction(state, fn, name, length);
- js_defglobal(state, name, JS_DONTENUM);
- }
- static void push_func_data(js_State *state, const char *name,
- js_CFunction fn, int length, unsigned int handle)
- {
- js_newcfunctionx(state, fn, name, length,
- (void *)(uintptr_t)handle, 0);
- }
- static const char *node_attr(unsigned int node, const char *name)
- {
- return br_find_attr(D, node, name);
- }
- static void push_attr(js_State *state, unsigned int node, const char *name,
- int null_if_missing)
- {
- const char *s = node_attr(node, name);
- if (s)
- js_pushstring(state, s);
- else if (null_if_missing)
- js_pushnull(state);
- else
- js_pushstring(state, "");
- }
- static unsigned int node_name(unsigned int node, char *buf, unsigned int cap)
- {
- struct br_node *n;
- const char *s;
- unsigned int i = 0;
- if (!D || node >= D->nnode || cap == 0)
- return 0;
- n = &D->nodes[node];
- if (n->type == BR_NODE_TEXT)
- s = "#text";
- else if (n->type == BR_NODE_COMMENT)
- s = "#comment";
- else if (n->type == BR_NODE_FRAGMENT)
- s = "#document-fragment";
- else if (n->tag == BR_TAG_UNKNOWN && n->name_off)
- s = D->attrs + n->name_off;
- else
- s = br_tag_name(n->tag);
- while (s && *s && i + 1 < cap) {
- char c = *s++;
- if (c >= 'a' && c <= 'z')
- c = (char)(c - 'a' + 'A');
- buf[i++] = c;
- }
- buf[i] = '\0';
- return i;
- }
- /* ---- DOM events ------------------------------------------------------- *
- *
- * Listeners live in a fixed table, one entry per (target, type, callback)
- * registration, and callbacks are retained through the engine registry. The
- * dispatcher walks the parent chain for bubbling and runs one listener at a
- * time so a handler can safely mutate the tree. `preventDefault` is tracked
- * per dispatch in a small event-state table and mirrored onto the event
- * object, so a submit handler can cancel the browser's default action. */
- #define JS_LISTENERS 64
- #define JS_EVENT_SLOTS 8
- #define JS_EVENT_TEMPLATES 16
- #define JS_TARGET_WINDOW 0xFFFFFFF0u
- #define JS_TARGET_DOCUMENT 0xFFFFFFF1u
- struct js_listener {
- unsigned char used;
- unsigned char capture;
- unsigned int target;
- char type[24];
- char ref[32];
- };
- struct js_event_state {
- int used;
- int prevented;
- int stopped;
- int immediate;
- char objref[32];
- };
- struct js_template {
- int used;
- char ref[32];
- };
- static struct js_listener listeners[JS_LISTENERS];
- static struct js_event_state events[JS_EVENT_SLOTS];
- static struct js_template event_templates[JS_EVENT_TEMPLATES];
- static void push_event_target(js_State *state, unsigned int target)
- {
- if (target == JS_TARGET_WINDOW)
- js_pushglobal(state);
- else if (target == JS_TARGET_DOCUMENT)
- js_getglobal(state, "document");
- else
- push_node(state, target + 1);
- }
- static void obj_set(js_State *state, int idx, const char *name)
- {
- /* The value was just pushed, so a negative object index moved down. */
- if (idx < 0)
- idx--;
- js_setproperty(state, idx, name);
- }
- static void obj_set_string(js_State *state, int idx, const char *name,
- const char *value)
- {
- js_pushstring(state, value ? value : "");
- obj_set(state, idx, name);
- }
- static void obj_set_bool(js_State *state, int idx, const char *name, int value)
- {
- js_pushboolean(state, value != 0);
- obj_set(state, idx, name);
- }
- static int event_slot(js_State *state)
- {
- int slot = (int)(uintptr_t)js_currentfunctiondata(state);
- if (slot < 0 || slot >= JS_EVENT_SLOTS)
- return -1;
- return slot;
- }
- static void event_preventdefault(js_State *state)
- {
- int slot = event_slot(state);
- if (slot >= 0) {
- struct js_event_state *ev = &events[slot];
- ev->prevented = 1;
- if (ev->objref[0]) {
- js_getregistry(state, ev->objref);
- if (js_isobject(state, -1)) {
- js_pushboolean(state, 1);
- js_setproperty(state, -2, "defaultPrevented");
- }
- js_pop(state, 1);
- }
- }
- js_pushundefined(state);
- }
- static void event_stoppropagation(js_State *state)
- {
- int slot = event_slot(state);
- if (slot >= 0)
- events[slot].stopped = 1;
- js_pushundefined(state);
- }
- static void event_stopimmediate(js_State *state)
- {
- int slot = event_slot(state);
- if (slot >= 0) {
- events[slot].stopped = 1;
- events[slot].immediate = 1;
- }
- js_pushundefined(state);
- }
- /* Event-object field helpers. Every dispatch owns a registry key for its
- * event object so preventDefault can update the object without access to
- * `this` (the stack API has no this accessor). */
- static void ev_set_string(js_State *state, int slot, const char *name,
- const char *value)
- {
- js_getregistry(state, events[slot].objref);
- js_pushstring(state, value ? value : "");
- js_setproperty(state, -2, name);
- js_pop(state, 1);
- }
- static void ev_set_bool(js_State *state, int slot, const char *name, int value)
- {
- js_getregistry(state, events[slot].objref);
- js_pushboolean(state, value != 0);
- js_setproperty(state, -2, name);
- js_pop(state, 1);
- }
- static void ev_set_number(js_State *state, int slot, const char *name,
- double value)
- {
- js_getregistry(state, events[slot].objref);
- js_pushnumber(state, value);
- js_setproperty(state, -2, name);
- js_pop(state, 1);
- }
- static void ev_set_target(js_State *state, int slot, const char *name,
- unsigned int target)
- {
- js_getregistry(state, events[slot].objref);
- push_event_target(state, target);
- js_setproperty(state, -2, name);
- js_pop(state, 1);
- }
- static int ev_get_bool(js_State *state, int slot, const char *name, int def)
- {
- int rv = def;
- js_getregistry(state, events[slot].objref);
- js_getproperty(state, -1, name);
- if (js_isboolean(state, -1))
- rv = js_toboolean(state, -1);
- js_pop(state, 2);
- return rv;
- }
- static void ev_get_string(js_State *state, int slot, const char *name,
- char *out, int cap, const char *def)
- {
- const char *s = def ? def : "";
- int n = 0;
- js_getregistry(state, events[slot].objref);
- js_getproperty(state, -1, name);
- if (js_isstring(state, -1))
- s = js_tostring(state, -1);
- while (s[n] && n + 1 < cap) {
- out[n] = s[n];
- n++;
- }
- out[n] = '\0';
- js_pop(state, 2);
- }
- static void event_bind_methods(js_State *state, int slot)
- {
- js_getregistry(state, events[slot].objref);
- def_func_data(state, "preventDefault", event_preventdefault, 0,
- (unsigned int)slot);
- def_func_data(state, "stopPropagation", event_stoppropagation, 0,
- (unsigned int)slot);
- def_func_data(state, "stopImmediatePropagation", event_stopimmediate, 0,
- (unsigned int)slot);
- js_pop(state, 1);
- }
- /* The event object is on top of the stack; move it into the registry and
- * fill in the standard fields. */
- static int event_prepare(js_State *state, unsigned int target)
- {
- int slot;
- for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
- if (!events[slot].used)
- break;
- if (slot == JS_EVENT_SLOTS)
- return -1;
- events[slot].used = 1;
- events[slot].prevented = 0;
- events[slot].stopped = 0;
- events[slot].immediate = 0;
- snprintf(events[slot].objref, sizeof(events[slot].objref),
- "jseventobj_%d", slot);
- js_setregistry(state, events[slot].objref);
- ev_set_bool(state, slot, "defaultPrevented", 0);
- ev_set_bool(state, slot, "isTrusted", 0);
- ev_set_number(state, slot, "timeStamp", (double)u_ticks_ms());
- ev_set_target(state, slot, "target", target);
- ev_set_target(state, slot, "currentTarget", target);
- ev_set_number(state, slot, "eventPhase", 2);
- event_bind_methods(state, slot);
- return slot;
- }
- static int listener_call(js_State *state, const struct js_listener *l,
- int slot, unsigned int current_target)
- {
- js_getregistry(state, l->ref);
- if (!js_iscallable(state, -1)) {
- js_pop(state, 1);
- return 0;
- }
- push_event_target(state, current_target);
- js_getregistry(state, events[slot].objref);
- if (js_pcall(state, 1)) {
- report_top(state);
- return 0;
- }
- js_pop(state, 1);
- return 1;
- }
- static void listener_phase(js_State *state, unsigned int target,
- const char *type, int phase, int slot)
- {
- int i;
- for (i = 0; i < JS_LISTENERS; i++) {
- struct js_listener *l = &listeners[i];
- if (!l->used || l->target != target ||
- strcmp(l->type, type) != 0)
- continue;
- if (phase == 1 && !l->capture)
- continue;
- if (phase == 2 && l->capture)
- continue;
- ev_set_target(state, slot, "currentTarget", target);
- listener_call(state, l, slot, target);
- if (events[slot].immediate)
- return;
- }
- }
- /* supplied_idx: 0 creates a fresh object, otherwise it is the argument
- * index of an Event supplied by JavaScript. Leaves a boolean result. */
- static void inline_attr_decode(const char *s, char *d, unsigned int cap)
- {
- unsigned int i = 0, n = 0;
- while (s && s[i] && n + 1 < cap) {
- if (s[i] == '&') {
- if (!strncmp(s + i, """, 6)) {
- d[n++] = '"'; i += 6; continue;
- }
- if (!strncmp(s + i, "'", 5)) {
- d[n++] = '\''; i += 5; continue;
- }
- if (!strncmp(s + i, "&", 5)) {
- d[n++] = '&'; i += 5; continue;
- }
- if (!strncmp(s + i, "<", 4)) {
- d[n++] = '<'; i += 4; continue;
- }
- if (!strncmp(s + i, ">", 4)) {
- d[n++] = '>'; i += 4; continue;
- }
- }
- d[n++] = s[i++];
- }
- d[n] = '\0';
- }
- /* Inline on<event> attributes run at the target and while bubbling, after
- * the registered listeners for that node. The handler gets the event and
- * the element as `this`; a false return prevents the default action. */
- static void run_inline_handler(js_State *state, unsigned int node,
- const char *type, int slot, int *prevented)
- {
- char name[40], body[512], src[640];
- const char *attr;
- int truthy;
- if (!D || node >= D->nnode || !events[slot].objref[0])
- return;
- snprintf(name, sizeof(name), "on%s", type);
- attr = br_find_attr(D, node, name);
- if (!attr || !attr[0])
- return;
- inline_attr_decode(attr, body, sizeof(body));
- snprintf(src, sizeof(src), "(function(event){ %s\n})", body);
- if (js_try(state)) {
- /* The throw already unwound this try frame. */
- js_pop(state, 1);
- return;
- }
- js_loadstring(state, "[inline]", src);
- /* The script evaluates the function expression; run it first, then
- * call the resulting function with the element as `this`. */
- js_pushundefined(state);
- if (js_pcall(state, 0) || !js_iscallable(state, -1)) {
- js_pop(state, 1);
- js_endtry(state);
- return;
- }
- push_node(state, node + 1);
- js_getregistry(state, events[slot].objref);
- if (js_pcall(state, 1)) {
- js_pop(state, 1);
- js_endtry(state);
- return;
- }
- truthy = js_toboolean(state, -1);
- js_pop(state, 1);
- js_endtry(state);
- if (!truthy && prevented)
- *prevented = 1;
- }
- static int dispatch_object(js_State *state, unsigned int target,
- int supplied_idx, const char *fallback,
- int def_bubbles, int def_cancelable)
- {
- unsigned int path[64];
- char type[32];
- int np = 0, slot, i, prevented;
- struct br_node *nd;
- if (supplied_idx)
- js_copy(state, supplied_idx);
- else
- js_newobject(state);
- slot = event_prepare(state, target);
- if (slot < 0) {
- js_pushboolean(state, 1);
- return 1;
- }
- ev_get_string(state, slot, "type", type, sizeof(type), fallback);
- if (!type[0]) {
- js_unref(state, events[slot].objref);
- events[slot].objref[0] = '\0';
- events[slot].used = 0;
- js_pushboolean(state, 1);
- return 1;
- }
- ev_set_string(state, slot, "type", type);
- ev_set_bool(state, slot, "bubbles",
- ev_get_bool(state, slot, "bubbles", def_bubbles));
- ev_set_bool(state, slot, "cancelable",
- ev_get_bool(state, slot, "cancelable", def_cancelable));
- path[np++] = target;
- if (target != JS_TARGET_WINDOW && target != JS_TARGET_DOCUMENT &&
- D && target < D->nnode) {
- nd = &D->nodes[target];
- while (nd->parent && nd->parent < D->nnode &&
- np < (int)(sizeof(path) / sizeof(path[0]))) {
- path[np++] = nd->parent;
- nd = &D->nodes[nd->parent];
- }
- }
- if (target != JS_TARGET_WINDOW)
- path[np++] = JS_TARGET_DOCUMENT;
- if (np < (int)(sizeof(path) / sizeof(path[0])))
- path[np++] = JS_TARGET_WINDOW;
- /* Capture from the outermost ancestor down to the parent. */
- for (i = np - 1; i > 0; i--) {
- if (events[slot].stopped)
- break;
- listener_phase(state, path[i], type, 1, slot);
- }
- /* Target phase: capture and bubble listeners in registration order. */
- if (!events[slot].stopped) {
- listener_phase(state, path[0], type, 0, slot);
- if (!events[slot].stopped)
- run_inline_handler(state, path[0], type, slot,
- &events[slot].prevented);
- }
- /* Bubble only for events that ask for it; stopPropagation stops the
- * remaining ancestors. */
- if (ev_get_bool(state, slot, "bubbles", def_bubbles)) {
- for (i = 1; i < np && !events[slot].stopped; i++) {
- listener_phase(state, path[i], type, 2, slot);
- if (!events[slot].stopped &&
- path[i] != JS_TARGET_WINDOW &&
- path[i] != JS_TARGET_DOCUMENT)
- run_inline_handler(state, path[i], type, slot,
- &events[slot].prevented);
- }
- }
- prevented = events[slot].prevented;
- js_unref(state, events[slot].objref);
- events[slot].objref[0] = '\0';
- events[slot].used = 0;
- js_pushboolean(state, prevented ? 0 : 1);
- return prevented ? 0 : 1;
- }
- static void add_listener(js_State *state, unsigned int target, int remove)
- {
- const char *type;
- int i;
- if (!js_iscallable(state, 2))
- return;
- type = js_tostring(state, 1);
- if (!type[0])
- return;
- if (!remove) {
- for (i = 0; i < JS_LISTENERS; i++)
- if (!listeners[i].used)
- break;
- if (i == JS_LISTENERS)
- return;
- listeners[i].used = 1;
- listeners[i].capture = js_isboolean(state, 3) &&
- js_toboolean(state, 3);
- listeners[i].target = target;
- snprintf(listeners[i].type, sizeof(listeners[i].type), "%s",
- type);
- js_copy(state, 2);
- snprintf(listeners[i].ref, sizeof(listeners[i].ref), "%s",
- js_ref(state));
- return;
- }
- for (i = 0; i < JS_LISTENERS; i++) {
- struct js_listener *l = &listeners[i];
- int eq;
- if (!l->used || l->target != target ||
- strcmp(l->type, type) != 0)
- continue;
- js_getregistry(state, l->ref);
- js_copy(state, 2);
- eq = js_equal(state);
- js_pop(state, 2);
- if (!eq)
- continue;
- js_unref(state, l->ref);
- l->used = 0;
- return;
- }
- }
- static void node_addlistener(js_State *state)
- {
- unsigned int node = (unsigned int)(uintptr_t)
- js_currentfunctiondata(state) - 1;
- add_listener(state, node, 0);
- }
- static void node_removelistener(js_State *state)
- {
- unsigned int node = (unsigned int)(uintptr_t)
- js_currentfunctiondata(state) - 1;
- add_listener(state, node, 1);
- }
- static void node_dispatchevent(js_State *state)
- {
- unsigned int node = (unsigned int)(uintptr_t)
- js_currentfunctiondata(state) - 1;
- if (!D || !node) {
- js_pushboolean(state, 1);
- return;
- }
- if (js_isobject(state, 1)) {
- dispatch_object(state, node, 1, "event", 1, 0);
- } else {
- char type[32];
- const char *s = js_tostring(state, 1);
- unsigned int i = 0;
- while (s[i] && i + 1 < sizeof(type)) {
- type[i] = s[i];
- i++;
- }
- type[i] = '\0';
- dispatch_object(state, node, 0, type, 1, 0);
- }
- }
- static void win_addlistener(js_State *state)
- {
- add_listener(state, JS_TARGET_WINDOW, 0);
- }
- static void win_removelistener(js_State *state)
- {
- add_listener(state, JS_TARGET_WINDOW, 1);
- }
- static void doc_addlistener(js_State *state)
- {
- add_listener(state, JS_TARGET_DOCUMENT, 0);
- }
- static void doc_removelistener(js_State *state)
- {
- add_listener(state, JS_TARGET_DOCUMENT, 1);
- }
- static void event_init(js_State *state)
- {
- int slot = (int)(uintptr_t)js_currentfunctiondata(state);
- const char *type;
- if (slot < 0 || slot >= JS_EVENT_TEMPLATES ||
- !event_templates[slot].used)
- return;
- type = js_tostring(state, 1);
- js_getregistry(state, event_templates[slot].ref);
- if (!js_isobject(state, -1)) {
- js_pop(state, 1);
- return;
- }
- obj_set_string(state, -1, "type", type);
- obj_set_bool(state, -1, "bubbles", js_toboolean(state, 2));
- obj_set_bool(state, -1, "cancelable", js_toboolean(state, 3));
- js_pop(state, 1);
- }
- static void event_build_object(js_State *state, const char *type,
- int bubbles, int cancelable, int with_init)
- {
- js_newobject(state);
- js_pushstring(state, type ? type : "");
- js_setproperty(state, -2, "type");
- js_pushboolean(state, bubbles != 0);
- js_setproperty(state, -2, "bubbles");
- js_pushboolean(state, cancelable != 0);
- js_setproperty(state, -2, "cancelable");
- js_pushboolean(state, 0);
- js_setproperty(state, -2, "defaultPrevented");
- if (with_init) {
- int i;
- for (i = 0; i < JS_EVENT_TEMPLATES; i++)
- if (!event_templates[i].used)
- break;
- if (i < JS_EVENT_TEMPLATES) {
- event_templates[i].used = 1;
- snprintf(event_templates[i].ref,
- sizeof(event_templates[i].ref),
- "jseventtmpl_%d", i);
- js_copy(state, -1);
- js_setregistry(state, event_templates[i].ref);
- def_func_data(state, "initEvent", event_init, 3,
- (unsigned int)i);
- }
- }
- }
- static void event_call(js_State *state)
- {
- const char *type = js_isdefined(state, 1) ? js_tostring(state, 1) : "";
- int bubbles = 0, cancelable = 0;
- if (js_isobject(state, 2)) {
- js_getproperty(state, 2, "bubbles");
- bubbles = js_toboolean(state, -1);
- js_pop(state, 1);
- js_getproperty(state, 2, "cancelable");
- cancelable = js_toboolean(state, -1);
- js_pop(state, 1);
- }
- event_build_object(state, type, bubbles, cancelable, 1);
- }
- static void doc_createevent(js_State *state)
- {
- const char *type = js_tostring(state, 1);
- event_build_object(state, type, 0, 0, 1);
- }
- static void custom_event_call(js_State *state)
- {
- event_call(state);
- if (js_isobject(state, 2))
- js_getproperty(state, 2, "detail");
- else
- js_pushnull(state);
- js_setproperty(state, -2, "detail");
- }
- static void mouse_event_call(js_State *state)
- {
- static const struct {
- const char *name;
- int is_number;
- } props[] = {
- { "clientX", 1 }, { "clientY", 1 }, { "screenX", 1 },
- { "screenY", 1 }, { "button", 1 }, { "buttons", 1 },
- { "ctrlKey", 0 }, { "shiftKey", 0 }, { "altKey", 0 },
- { "metaKey", 0 }
- };
- unsigned int i;
- event_call(state);
- if (!js_isobject(state, 2))
- return;
- for (i = 0; i < sizeof(props) / sizeof(props[0]); i++) {
- js_getproperty(state, 2, props[i].name);
- if (props[i].is_number) {
- double v = js_isnumber(state, -1) ?
- js_tonumber(state, -1) : 0;
- js_pop(state, 1);
- js_pushnumber(state, v);
- } else {
- int v = js_toboolean(state, -1);
- js_pop(state, 1);
- js_pushboolean(state, v);
- }
- js_setproperty(state, -2, props[i].name);
- }
- }
- int js_browser_event(unsigned int node, const char *type, int bubbles,
- int cancelable)
- {
- int slot, rv;
- if (!J || !D)
- return 1;
- for (slot = 0; slot < JS_EVENT_SLOTS; slot++)
- if (!events[slot].used)
- break;
- if (slot == JS_EVENT_SLOTS)
- return 1;
- js_setlimit(J, JS_RUN_LIMIT, 0);
- rv = dispatch_object(J, node, 0, type, bubbles, cancelable);
- js_pop(J, 1);
- js_runjobs(J);
- return rv;
- }
- static unsigned int node_type_value(unsigned int node)
- {
- struct br_node *n;
- if (!D || node >= D->nnode)
- return 0;
- n = &D->nodes[node];
- if (n->type == BR_NODE_TEXT)
- return 3;
- if (n->type == BR_NODE_COMMENT)
- return 8;
- if (n->type == BR_NODE_FRAGMENT)
- return 11;
- return 1;
- }
- static void push_child_list(js_State *state, unsigned int node, int elements)
- {
- struct br_node *n;
- unsigned int c, i = 0;
- js_newarray(state);
- if (!D || node >= D->nnode)
- return;
- n = &D->nodes[node];
- for (c = n->first; c; c = D->nodes[c].next) {
- if (elements && D->nodes[c].type != BR_NODE_ELEM)
- continue;
- push_node(state, c + 1);
- js_setindex(state, -2, (int)i++);
- }
- }
- static unsigned int node_prev_sibling(unsigned int node)
- {
- unsigned int p, c, prev = 0;
- if (!D || node >= D->nnode)
- return 0;
- p = D->nodes[node].parent;
- for (c = D->nodes[p].first; c && c != node; c = D->nodes[c].next)
- prev = c;
- return prev;
- }
- /* ---- inline style and dataset objects ---- */
- static int ci_eq_n(const char *a, const char *b, unsigned int n)
- {
- unsigned int i;
- for (i = 0; i < n; i++) {
- char ca = a[i], cb = b[i];
- if (ca >= 'A' && ca <= 'Z')
- ca = (char)(ca - 'A' + 'a');
- if (cb >= 'A' && cb <= 'Z')
- cb = (char)(cb - 'A' + 'a');
- if (ca != cb)
- return 0;
- }
- return 1;
- }
- /* camelCase JS property -> CSS property ("marginTop" -> "margin-top"). */
- static void css_name(const char *name, char *out, unsigned int cap)
- {
- unsigned int n = 0, i;
- if (!strcmp(name, "cssFloat")) {
- if (cap > 6)
- memcpy(out, "float", 6);
- else if (cap)
- out[0] = '\0';
- return;
- }
- for (i = 0; name[i] && n + 2 < cap; i++) {
- char c = name[i];
- if (c >= 'A' && c <= 'Z') {
- if (n == 0 || out[n - 1] != '-')
- out[n++] = '-';
- out[n++] = (char)(c - 'A' + 'a');
- } else {
- out[n++] = c;
- }
- }
- if (cap)
- out[n] = '\0';
- }
- /* camelCase dataset property -> attribute name ("fooBar" -> "data-foo-bar"). */
- static void data_name(const char *name, char *out, unsigned int cap)
- {
- unsigned int n = 0, i;
- for (i = 0; i < 5 && n + 1 < cap; i++)
- out[n++] = "data-"[i];
- for (i = 0; name[i] && n + 2 < cap; i++) {
- char c = name[i];
- if (c >= 'A' && c <= 'Z') {
- out[n++] = '-';
- c = (char)(c - 'A' + 'a');
- }
- out[n++] = c;
- }
- if (cap)
- out[n] = '\0';
- }
- static int style_lookup(const char *style, const char *prop, char *out,
- unsigned int cap)
- {
- unsigned int i = 0, nl = (unsigned int)strlen(prop);
- while (style && style[i]) {
- unsigned int ns, ne, vs, ve, a, b, k;
- while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
- i++;
- if (!style[i])
- break;
- ns = i;
- while (style[i] && style[i] != ':' && style[i] != ';')
- i++;
- ne = i;
- if (style[i] != ':') {
- if (style[i] == ';')
- i++;
- continue;
- }
- i++;
- while (style[i] == ' ' || style[i] == '\t')
- i++;
- vs = i;
- while (style[i] && style[i] != ';')
- i++;
- ve = i;
- a = ns;
- b = ne;
- while (a < b && (style[a] == ' ' || style[a] == '\t'))
- a++;
- while (b > a && (style[b - 1] == ' ' || style[b - 1] == '\t'))
- b--;
- while (ve > vs && (style[ve - 1] == ' ' || style[ve - 1] == '\t'))
- ve--;
- if (b - a == nl && ci_eq_n(style + a, prop, nl)) {
- for (k = 0; k < ve - vs && k + 1 < cap; k++)
- out[k] = style[vs + k];
- out[k < cap ? k : cap - 1] = '\0';
- return 1;
- }
- }
- return 0;
- }
- static unsigned int style_count(const char *style)
- {
- unsigned int i = 0, n = 0;
- while (style && style[i]) {
- while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
- i++;
- if (!style[i])
- break;
- while (style[i] && style[i] != ';')
- i++;
- n++;
- }
- return n;
- }
- static unsigned int style_span(const char *style, unsigned int i)
- {
- while (style[i] == ' ' || style[i] == ';' || style[i] == '\t')
- i++;
- return i;
- }
- static void style_update(unsigned int node, const char *prop,
- const char *value, int remove)
- {
- const char *old = br_find_attr(D, node, "style");
- char arr[512];
- unsigned int n = 0, i = 0, nl = (unsigned int)strlen(prop);
- int replaced = 0;
- if (remove && !old)
- return;
- while (old && old[i] && n + 2 < sizeof(arr)) {
- unsigned int start = style_span(old, i);
- unsigned int ns, ne, ve, a, b, k;
- i = start;
- if (!old[i])
- break;
- ns = i;
- while (old[i] && old[i] != ':' && old[i] != ';')
- i++;
- ne = i;
- if (old[i] == ':') {
- i++;
- while (old[i] == ' ' || old[i] == '\t')
- i++;
- while (old[i] && old[i] != ';')
- i++;
- }
- ve = i;
- a = ns;
- b = ne;
- while (a < b && (old[a] == ' ' || old[a] == '\t'))
- a++;
- while (b > a && (old[b - 1] == ' ' || old[b - 1] == '\t'))
- b--;
- if (b - a == nl && ci_eq_n(old + a, prop, nl)) {
- replaced = 1;
- if (remove || !value || !value[0])
- continue;
- }
- for (k = ns; k < ve && n + 1 < sizeof(arr); k++)
- arr[n++] = old[k];
- if (n + 1 < sizeof(arr))
- arr[n++] = ';';
- }
- if (replaced && (remove || !value || !value[0])) {
- arr[n] = '\0';
- br_set_attr(D, node, "style", arr, n);
- if (host.changed)
- host.changed();
- return;
- }
- if (value && value[0] && n + nl + strlen(value) + 3 < sizeof(arr)) {
- for (i = 0; i < nl; i++)
- arr[n++] = prop[i];
- arr[n++] = ':';
- for (i = 0; value[i]; i++)
- arr[n++] = value[i];
- arr[n++] = ';';
- }
- arr[n] = '\0';
- br_set_attr(D, node, "style", arr, n);
- if (host.changed)
- host.changed();
- }
- static void style_getproperty(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- char val[256];
- if (style_lookup(br_find_attr(D, node, "style"),
- js_tostring(state, 1), val, sizeof(val)))
- js_pushstring(state, val);
- else
- js_pushstring(state, "");
- }
- static void style_setproperty(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- style_update(node, js_tostring(state, 1),
- js_tostring(state, 2), 0);
- }
- static void style_removeproperty(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *prop = js_tostring(state, 1);
- char old[256];
- int had = style_lookup(br_find_attr(D, node, "style"), prop,
- old, sizeof(old));
- style_update(node, prop, "", 1);
- if (had)
- js_pushstring(state, old);
- else
- js_pushstring(state, "");
- }
- static int style_has(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- const char *style;
- char prop[64], val[256];
- if (!D || node >= D->nnode)
- return 0;
- style = br_find_attr(D, node, "style");
- if (!strcmp(name, "cssText")) {
- js_pushstring(state, style ? style : "");
- return 1;
- }
- if (!strcmp(name, "length")) {
- js_pushnumber(state, style_count(style));
- return 1;
- }
- if (!strcmp(name, "getPropertyValue")) {
- push_func_data(state, name, style_getproperty, 1, node + 1);
- return 1;
- }
- if (!strcmp(name, "setProperty")) {
- push_func_data(state, name, style_setproperty, 2, node + 1);
- return 1;
- }
- if (!strcmp(name, "removeProperty")) {
- push_func_data(state, name, style_removeproperty, 1, node + 1);
- return 1;
- }
- css_name(name, prop, sizeof(prop));
- if (style_lookup(style, prop, val, sizeof(val)))
- js_pushstring(state, val);
- else
- js_pushstring(state, "");
- return 1;
- }
- static int style_put(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- const char *value;
- char prop[64];
- if (!D || node >= D->nnode)
- return 0;
- value = js_tostring(state, -1);
- if (!strcmp(name, "cssText")) {
- br_set_attr(D, node, "style", value, (unsigned int)strlen(value));
- if (host.changed)
- host.changed();
- return 1;
- }
- css_name(name, prop, sizeof(prop));
- style_update(node, prop, value, 0);
- return 1;
- }
- static void push_style_object(js_State *state, unsigned int node)
- {
- char key[32];
- snprintf(key, sizeof(key), "sty_%u", node + 1);
- js_getregistry(state, key);
- if (!js_isundefined(state, -1))
- return;
- js_pop(state, 1);
- js_getregistry(state, "wrapproto");
- js_newuserdatax(state, "style", (void *)(uintptr_t)(node + 1),
- style_has, style_put, 0, 0);
- js_copy(state, -1);
- js_setregistry(state, key);
- }
- static int dataset_has(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- char attr[64];
- const char *value;
- if (!D || node >= D->nnode)
- return 0;
- data_name(name, attr, sizeof(attr));
- value = br_find_attr(D, node, attr);
- if (value)
- js_pushstring(state, value);
- else
- js_pushundefined(state);
- return 1;
- }
- static int dataset_put(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- char attr[64];
- const char *value = js_tostring(state, -1);
- if (!D || node >= D->nnode)
- return 0;
- data_name(name, attr, sizeof(attr));
- br_set_attr(D, node, attr, value, (unsigned int)strlen(value));
- if (host.changed)
- host.changed();
- return 1;
- }
- static int dataset_delete(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- char attr[64];
- (void)state;
- if (!D || node >= D->nnode)
- return 0;
- data_name(name, attr, sizeof(attr));
- br_remove_attr(D, node, attr);
- if (host.changed)
- host.changed();
- return 1;
- }
- static void push_dataset(js_State *state, unsigned int node)
- {
- char key[32];
- snprintf(key, sizeof(key), "ds_%u", node + 1);
- js_getregistry(state, key);
- if (!js_isundefined(state, -1))
- return;
- js_pop(state, 1);
- js_getregistry(state, "wrapproto");
- js_newuserdatax(state, "dataset", (void *)(uintptr_t)(node + 1),
- dataset_has, dataset_put, dataset_delete, 0);
- js_copy(state, -1);
- js_setregistry(state, key);
- }
- static void node_class_set(unsigned int node, const char *classes)
- {
- br_set_attr(D, node, "class", classes,
- (unsigned int)strlen(classes));
- if (host.changed)
- host.changed();
- }
- static int class_has(const char *classes, const char *name)
- {
- unsigned int i = 0;
- if (!classes)
- return 0;
- while (classes[i]) {
- unsigned int start;
- while (classes[i] == ' ' || classes[i] == '\t')
- i++;
- start = i;
- while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
- i++;
- if (i - start == strlen(name) &&
- !strncmp(classes + start, name, i - start))
- return 1;
- }
- return 0;
- }
- static void class_add(unsigned int node, const char *name, int add)
- {
- const char *old = node_attr(node, "class");
- char buf[256];
- unsigned int n = 0, i = 0;
- if (add) {
- if (class_has(old, name))
- return;
- if (old && old[0]) {
- while (old[i] && n + 1 < sizeof(buf))
- buf[n++] = old[i++];
- if (n + 1 < sizeof(buf))
- buf[n++] = ' ';
- }
- i = 0;
- while (name[i] && n + 1 < sizeof(buf))
- buf[n++] = name[i++];
- } else {
- if (!old)
- return;
- while (old[i]) {
- unsigned int start;
- while (old[i] == ' ' || old[i] == '\t')
- i++;
- start = i;
- while (old[i] && old[i] != ' ' && old[i] != '\t')
- i++;
- if (i - start == strlen(name) &&
- !strncmp(old + start, name, i - start))
- continue;
- if (n && n + 1 < sizeof(buf))
- buf[n++] = ' ';
- {
- unsigned int k;
- for (k = start; k < i && n + 1 < sizeof(buf);
- k++)
- buf[n++] = old[k];
- }
- }
- }
- buf[n] = '\0';
- node_class_set(node, buf);
- }
- static void node_classlist_add(js_State *state)
- {
- class_add(node_of(js_currentfunctiondata(state)),
- js_tostring(state, 1), 1);
- }
- static void node_classlist_remove(js_State *state)
- {
- class_add(node_of(js_currentfunctiondata(state)),
- js_tostring(state, 1), 0);
- }
- static void node_classlist_toggle(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *name = js_tostring(state, 1);
- int has = class_has(node_attr(node, "class"), name);
- int want = !has;
- if (js_isdefined(state, 2))
- want = js_toboolean(state, 2);
- if (want != has)
- class_add(node, name, want);
- js_pushboolean(state, want);
- }
- static void node_classlist_contains(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- js_pushboolean(state, class_has(node_attr(node, "class"),
- js_tostring(state, 1)));
- }
- static unsigned int class_count(const char *classes)
- {
- unsigned int i = 0, n = 0;
- if (!classes)
- return 0;
- while (classes[i]) {
- while (classes[i] == ' ' || classes[i] == '\t')
- i++;
- if (!classes[i])
- break;
- n++;
- while (classes[i] && classes[i] != ' ' && classes[i] != '\t')
- i++;
- }
- return n;
- }
- static void push_attributes(js_State *state, unsigned int node)
- {
- struct br_node *n;
- const char *p, *end;
- unsigned int count = 0;
- js_newobject(state);
- if (!D || node >= D->nnode)
- return;
- n = &D->nodes[node];
- p = D->attrs + n->extra_off;
- end = p + n->extra_len;
- while (p + 1 < end) {
- const char *an = p;
- const char *av;
- p += strlen(p) + 1;
- if (p >= end)
- break;
- av = p;
- p += strlen(p) + 1;
- js_newobject(state);
- js_pushstring(state, an);
- js_setproperty(state, -2, "name");
- js_pushstring(state, av);
- js_setproperty(state, -2, "value");
- js_pushboolean(state, 1);
- js_setproperty(state, -2, "specified");
- /* Array-like: attributes[i] and attributes[name] both work. */
- js_copy(state, -1);
- js_setproperty(state, -3, an);
- js_setindex(state, -2, (int)count);
- count++;
- }
- js_pushnumber(state, count);
- js_setproperty(state, -2, "length");
- }
- static void push_classlist(js_State *state, unsigned int node)
- {
- js_newobject(state);
- def_func_data(state, "add", node_classlist_add, 1, node + 1);
- def_func_data(state, "remove", node_classlist_remove, 1, node + 1);
- def_func_data(state, "toggle", node_classlist_toggle, 1, node + 1);
- def_func_data(state, "contains", node_classlist_contains, 1, node + 1);
- js_pushnumber(state, class_count(node_attr(node, "class")));
- js_setproperty(state, -2, "length");
- }
- static void node_getattr(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- push_attr(state, node, js_tostring(state, 1), 1);
- }
- static void node_setattr(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *name = js_tostring(state, 1);
- const char *value = js_tostring(state, 2);
- char lower[64];
- unsigned int i;
- for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
- char c = name[i];
- if (c >= 'A' && c <= 'Z')
- c = (char)(c - 'A' + 'a');
- lower[i] = c;
- }
- lower[i] = '\0';
- br_set_attr(D, node, lower, value, (unsigned int)strlen(value));
- if (host.changed)
- host.changed();
- }
- static void node_removeattr(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *name = js_tostring(state, 1);
- char lower[64];
- unsigned int i;
- for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
- char c = name[i];
- if (c >= 'A' && c <= 'Z')
- c = (char)(c - 'A' + 'a');
- lower[i] = c;
- }
- lower[i] = '\0';
- br_remove_attr(D, node, lower);
- if (host.changed)
- host.changed();
- }
- static void node_hasattr(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- js_pushboolean(state, node_attr(node, js_tostring(state, 1)) != 0);
- }
- static void node_appendchild(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int child = arg_node(state, 1);
- if (br_append_child(D, node, child) != 0) {
- js_pushnull(state);
- return;
- }
- if (host.changed)
- host.changed();
- push_node(state, child);
- }
- static void node_insertbefore(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int child = arg_node(state, 1);
- unsigned int before = 0;
- if (!js_isnull(state, 2) && !js_isundefined(state, 2))
- before = arg_node(state, 2);
- if (br_insert_before(D, node, child, before) != 0) {
- js_pushnull(state);
- return;
- }
- if (host.changed)
- host.changed();
- push_node(state, child);
- }
- static void node_removechild(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int child = arg_node(state, 1);
- if (br_remove_child(D, node, child) != 0) {
- js_pushnull(state);
- return;
- }
- if (host.changed)
- host.changed();
- push_node(state, child);
- }
- static void node_replacechild(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int child = arg_node(state, 1);
- unsigned int old = arg_node(state, 2);
- br_insert_before(D, node, child, old);
- br_remove_child(D, node, old);
- if (host.changed)
- host.changed();
- push_node(state, old);
- }
- static void node_clone(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int h = br_clone_node(D, node + 1,
- js_toboolean(state, 1));
- push_node(state, h);
- }
- static void node_contains(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int other = arg_node(state, 1);
- unsigned int p = other;
- while (1) {
- if (p == node) {
- js_pushboolean(state, 1);
- return;
- }
- if (p == 0)
- break;
- p = D->nodes[p].parent;
- }
- js_pushboolean(state, 0);
- }
- static void node_haschildren(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- js_pushboolean(state, node < D->nnode && D->nodes[node].first != 0);
- }
- static void node_remove(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int parent = node < D->nnode ? D->nodes[node].parent : 0;
- (void)state;
- if (parent)
- br_remove_child(D, parent, node + 1);
- if (host.changed)
- host.changed();
- }
- static void node_matches(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- js_pushboolean(state, br_matches(D, node + 1,
- js_tostring(state, 1)));
- }
- static void node_click(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- if (host.click)
- host.click(node);
- js_pushundefined(state);
- }
- static void node_getelementsbytagname(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *name = js_tostring(state, 1);
- unsigned int out[256];
- unsigned int n = br_query_all(D, node + 1, name, out, 256);
- js_newarray(state);
- for (unsigned int i = 0; i < n; i++) {
- push_node(state, out[i]);
- js_setindex(state, -2, (int)i);
- }
- }
- static void node_getelementsbyclassname(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *name = js_tostring(state, 1);
- char sel[256];
- unsigned int n = 0, i = 0;
- unsigned int out[256], count;
- while (name[i] && n + 2 < sizeof(sel)) {
- while (name[i] == ' ')
- i++;
- if (!name[i])
- break;
- sel[n++] = '.';
- while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
- sel[n++] = name[i++];
- }
- sel[n] = '\0';
- count = br_query_all(D, node + 1, sel, out, 256);
- js_newarray(state);
- for (i = 0; i < count; i++) {
- push_node(state, out[i]);
- js_setindex(state, -2, (int)i);
- }
- }
- static void node_queryselector(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int out[1];
- unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
- out, 1);
- if (n)
- push_node(state, out[0]);
- else
- js_pushnull(state);
- }
- static void node_queryselectorall(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- unsigned int out[256];
- unsigned int n = br_query_all(D, node + 1, js_tostring(state, 1),
- out, 256);
- js_newarray(state);
- for (unsigned int i = 0; i < n; i++) {
- push_node(state, out[i]);
- js_setindex(state, -2, (int)i);
- }
- }
- static void node_getrect(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- int x = 0, y = 0, w = 0, h = 0;
- if (host.rect)
- host.rect(node, &x, &y, &w, &h);
- js_newobject(state);
- js_pushnumber(state, y); js_setproperty(state, -2, "top");
- js_pushnumber(state, x); js_setproperty(state, -2, "left");
- js_pushnumber(state, x + w); js_setproperty(state, -2, "right");
- js_pushnumber(state, y + h); js_setproperty(state, -2, "bottom");
- js_pushnumber(state, w); js_setproperty(state, -2, "width");
- js_pushnumber(state, h); js_setproperty(state, -2, "height");
- }
- static void node_noop(js_State *state)
- {
- (void)state;
- }
- static void node_push_text(js_State *state, unsigned int node)
- {
- unsigned int cap = D->text_used + 1;
- char *buf;
- unsigned int len;
- if (cap < 32)
- cap = 32;
- buf = (char *)malloc(cap);
- if (!buf) {
- js_pushstring(state, "");
- return;
- }
- len = br_text_content(D, node, buf, cap);
- js_pushlstring(state, buf, (int)len);
- free(buf);
- }
- static unsigned int node_form_ancestor(unsigned int node)
- {
- while (node && node < D->nnode) {
- if (D->nodes[node].type == BR_NODE_ELEM &&
- D->nodes[node].tag == BR_TAG_FORM)
- return node;
- node = D->nodes[node].parent;
- }
- return 0;
- }
- static void push_form_elements(js_State *state, unsigned int form)
- {
- unsigned int out[128];
- int n = 0, i;
- if (host.form_elements)
- n = host.form_elements(form, out, (int)(sizeof(out) /
- sizeof(out[0])));
- js_newarray(state);
- for (i = 0; i < n; i++) {
- const char *name;
- push_node(state, out[i] + 1);
- js_setindex(state, -2, i);
- name = br_find_attr(D, out[i], "name");
- if (name && name[0]) {
- push_node(state, out[i] + 1);
- js_setproperty(state, -2, name);
- }
- }
- }
- static void form_submit_js(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- if (host.form_submit)
- host.form_submit(node);
- }
- static void form_reset_js(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- if (host.form_reset)
- host.form_reset(node);
- }
- /* Userdata property hooks: every element wrapper carries node + 1. */
- static int node_has(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- struct br_node *n;
- char buf[64];
- if (!D || node >= D->nnode)
- return 0;
- n = &D->nodes[node];
- if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM) {
- if (!strcmp(name, "elements")) {
- push_form_elements(state, node);
- return 1;
- }
- if (!strcmp(name, "length")) {
- unsigned int out[128];
- int count = 0;
- if (host.form_elements)
- count = host.form_elements(node, out,
- (int)(sizeof(out) / sizeof(out[0])));
- js_pushnumber(state, count);
- return 1;
- }
- if (!strcmp(name, "submit")) {
- push_func_data(state, "submit", form_submit_js, 0,
- node + 1);
- return 1;
- }
- if (!strcmp(name, "reset")) {
- push_func_data(state, "reset", form_reset_js, 0,
- node + 1);
- return 1;
- }
- }
- if (!strcmp(name, "form")) {
- unsigned int f;
- if (n->type == BR_NODE_ELEM && n->tag == BR_TAG_FORM)
- f = 0;
- else
- f = node_form_ancestor(node);
- if (f)
- push_node(state, f + 1);
- else
- js_pushnull(state);
- return 1;
- }
- if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
- node_push_text(state, node);
- return 1;
- }
- if (!strcmp(name, "nodeValue")) {
- if (n->type == BR_NODE_TEXT || n->type == BR_NODE_COMMENT)
- js_pushlstring(state, D->text + n->text_off,
- (int)n->text_len);
- else
- js_pushnull(state);
- return 1;
- }
- if (!strcmp(name, "nodeType")) {
- js_pushnumber(state, node_type_value(node));
- return 1;
- }
- if (!strcmp(name, "nodeName") || !strcmp(name, "tagName")) {
- node_name(node, buf, sizeof(buf));
- js_pushstring(state, buf);
- return 1;
- }
- if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) {
- unsigned int p = n->parent;
- push_node(state, p ? p + 1 : 0);
- return 1;
- }
- if (!strcmp(name, "childNodes")) {
- push_child_list(state, node, 0);
- return 1;
- }
- if (!strcmp(name, "children")) {
- push_child_list(state, node, 1);
- return 1;
- }
- if (!strcmp(name, "firstChild")) {
- push_node(state, n->first ? n->first + 1 : 0);
- return 1;
- }
- if (!strcmp(name, "lastChild")) {
- push_node(state, n->last ? n->last + 1 : 0);
- return 1;
- }
- if (!strcmp(name, "firstElementChild") ||
- !strcmp(name, "lastElementChild")) {
- unsigned int c = n->first;
- unsigned int found = 0;
- if (!strcmp(name, "lastElementChild")) {
- for (c = n->first; c; c = D->nodes[c].next)
- if (D->nodes[c].type == BR_NODE_ELEM)
- found = c;
- } else {
- while (c && D->nodes[c].type != BR_NODE_ELEM)
- c = D->nodes[c].next;
- found = c;
- }
- push_node(state, found ? found + 1 : 0);
- return 1;
- }
- if (!strcmp(name, "nextSibling") || !strcmp(name, "nextElementSibling")) {
- unsigned int c = n->next;
- if (!strcmp(name, "nextElementSibling"))
- while (c && D->nodes[c].type != BR_NODE_ELEM)
- c = D->nodes[c].next;
- push_node(state, c ? c + 1 : 0);
- return 1;
- }
- if (!strcmp(name, "previousSibling") ||
- !strcmp(name, "previousElementSibling")) {
- unsigned int c = node_prev_sibling(node);
- if (!strcmp(name, "previousElementSibling"))
- while (c && D->nodes[c].type != BR_NODE_ELEM)
- c = node_prev_sibling(c);
- push_node(state, c ? c + 1 : 0);
- return 1;
- }
- if (!strcmp(name, "childElementCount")) {
- unsigned int c, count = 0;
- for (c = n->first; c; c = D->nodes[c].next)
- if (D->nodes[c].type == BR_NODE_ELEM)
- count++;
- js_pushnumber(state, count);
- return 1;
- }
- if (n->tag == BR_TAG_A || n->tag == BR_TAG_AREA) {
- if (!strcmp(name, "href") || !strcmp(name, "protocol") ||
- !strcmp(name, "host") || !strcmp(name, "hostname") ||
- !strcmp(name, "port") || !strcmp(name, "pathname") ||
- !strcmp(name, "search") || !strcmp(name, "hash") ||
- !strcmp(name, "origin")) {
- push_element_url(state, node, name);
- return 1;
- }
- }
- if (!strcmp(name, "id")) { push_attr(state, node, "id", 0); return 1; }
- if (!strcmp(name, "className")) {
- push_attr(state, node, "class", 0);
- return 1;
- }
- if (!strcmp(name, "href")) { push_attr(state, node, "href", 0); return 1; }
- if (!strcmp(name, "src")) { push_attr(state, node, "src", 0); return 1; }
- if (!strcmp(name, "value")) {
- char buf[128];
- if (host.form_value && host.form_value(node, buf, sizeof(buf)))
- js_pushstring(state, buf);
- else
- push_attr(state, node, "value", 0);
- return 1;
- }
- if (!strcmp(name, "type")) { push_attr(state, node, "type", 0); return 1; }
- if (!strcmp(name, "name")) { push_attr(state, node, "name", 0); return 1; }
- if (!strcmp(name, "alt")) { push_attr(state, node, "alt", 0); return 1; }
- if (!strcmp(name, "title")) { push_attr(state, node, "title", 0); return 1; }
- if (!strcmp(name, "checked")) {
- int c = host.form_checked ? host.form_checked(node) : -1;
- js_pushboolean(state, c >= 0 ? c : node_attr(node, name) != 0);
- return 1;
- }
- if (!strcmp(name, "selectedIndex")) {
- int c = host.form_selected ? host.form_selected(node) : -1;
- js_pushnumber(state, c >= 0 ? c : 0);
- return 1;
- }
- if (!strcmp(name, "selected")) {
- int c = host.form_selected ? host.form_selected(node) : -1;
- if (c >= 0)
- js_pushboolean(state, c != 0);
- else
- js_pushboolean(state, node_attr(node, name) != 0);
- return 1;
- }
- if (!strcmp(name, "disabled")) {
- js_pushboolean(state, node_attr(node, name) != 0);
- return 1;
- }
- if (!strcmp(name, "style")) {
- push_style_object(state, node);
- return 1;
- }
- if (!strcmp(name, "dataset") || !strcmp(name, "domStringMap")) {
- push_dataset(state, node);
- return 1;
- }
- if (!strcmp(name, "classList")) {
- push_classlist(state, node);
- return 1;
- }
- if (!strcmp(name, "attributes")) {
- push_attributes(state, node);
- return 1;
- }
- if (!strcmp(name, "innerHTML") || !strcmp(name, "outerHTML")) {
- char key[32];
- snprintf(key, sizeof(key), "html_%u", node + 1);
- js_getregistry(state, key);
- if (js_isundefined(state, -1)) {
- js_pop(state, 1);
- js_pushstring(state, "");
- }
- return 1;
- }
- if (!strcmp(name, "ownerDocument")) {
- js_getglobal(state, "document");
- return 1;
- }
- if (!strcmp(name, "getAttribute"))
- { push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
- if (!strcmp(name, "setAttribute"))
- { push_func_data(state, "setAttribute", node_setattr, 2, node + 1); return 1; }
- if (!strcmp(name, "removeAttribute"))
- { push_func_data(state, "removeAttribute", node_removeattr, 1, node + 1); return 1; }
- if (!strcmp(name, "hasAttribute"))
- { push_func_data(state, "hasAttribute", node_hasattr, 1, node + 1); return 1; }
- if (!strcmp(name, "appendChild"))
- { push_func_data(state, "appendChild", node_appendchild, 1, node + 1); return 1; }
- if (!strcmp(name, "insertBefore"))
- { push_func_data(state, "insertBefore", node_insertbefore, 2, node + 1); return 1; }
- if (!strcmp(name, "removeChild"))
- { push_func_data(state, "removeChild", node_removechild, 1, node + 1); return 1; }
- if (!strcmp(name, "replaceChild"))
- { push_func_data(state, "replaceChild", node_replacechild, 2, node + 1); return 1; }
- if (!strcmp(name, "cloneNode"))
- { push_func_data(state, "cloneNode", node_clone, 1, node + 1); return 1; }
- if (!strcmp(name, "contains"))
- { push_func_data(state, "contains", node_contains, 1, node + 1); return 1; }
- if (!strcmp(name, "hasChildNodes"))
- { push_func_data(state, "hasChildNodes", node_haschildren, 0, node + 1); return 1; }
- if (!strcmp(name, "remove"))
- { push_func_data(state, "remove", node_remove, 0, node + 1); return 1; }
- if (!strcmp(name, "matches") || !strcmp(name, "webkitMatchesSelector") ||
- !strcmp(name, "mozMatchesSelector") ||
- !strcmp(name, "msMatchesSelector"))
- { push_func_data(state, name, node_matches, 1, node + 1); return 1; }
- if (!strcmp(name, "getElementsByTagName"))
- { push_func_data(state, "getElementsByTagName", node_getelementsbytagname, 1, node + 1); return 1; }
- if (!strcmp(name, "getElementsByClassName"))
- { push_func_data(state, "getElementsByClassName", node_getelementsbyclassname, 1, node + 1); return 1; }
- if (!strcmp(name, "querySelector"))
- { push_func_data(state, "querySelector", node_queryselector, 1, node + 1); return 1; }
- if (!strcmp(name, "querySelectorAll"))
- { push_func_data(state, "querySelectorAll", node_queryselectorall, 1, node + 1); return 1; }
- if (!strcmp(name, "addEventListener"))
- { push_func_data(state, "addEventListener", node_addlistener, 2, node + 1); return 1; }
- if (!strcmp(name, "removeEventListener"))
- { push_func_data(state, "removeEventListener", node_removelistener, 2, node + 1); return 1; }
- if (!strcmp(name, "dispatchEvent"))
- { push_func_data(state, "dispatchEvent", node_dispatchevent, 1, node + 1); return 1; }
- if (!strcmp(name, "getBoundingClientRect"))
- { push_func_data(state, "getBoundingClientRect", node_getrect, 0, node + 1); return 1; }
- if (!strcmp(name, "getClientRects")) {
- js_newarray(state);
- return 1;
- }
- if (!strcmp(name, "offsetWidth") || !strcmp(name, "offsetHeight") ||
- !strcmp(name, "clientWidth") || !strcmp(name, "clientHeight") ||
- !strcmp(name, "scrollWidth") || !strcmp(name, "scrollHeight")) {
- int x = 0, y = 0, w = 0, h = 0;
- if (host.rect)
- host.rect(node, &x, &y, &w, &h);
- js_pushnumber(state, (!strcmp(name, "offsetHeight") ||
- !strcmp(name, "clientHeight") ||
- !strcmp(name, "scrollHeight")) ? h : w);
- return 1;
- }
- if (!strcmp(name, "scrollTop") || !strcmp(name, "scrollLeft")) {
- js_pushnumber(state, 0);
- return 1;
- }
- if (!strcmp(name, "click")) {
- push_func_data(state, "click", node_click, 0, node + 1);
- return 1;
- }
- if (!strcmp(name, "focus") || !strcmp(name, "blur")) {
- push_func_data(state, name, node_noop, 0, node + 1);
- return 1;
- }
- return 0;
- }
- static void node_set_string(unsigned int node, const char *name,
- const char *value)
- {
- br_set_attr(D, node, name, value, (unsigned int)strlen(value));
- if (host.changed)
- host.changed();
- }
- static int node_put(js_State *state, void *p, const char *name)
- {
- unsigned int node = node_of(p);
- if (!D || node >= D->nnode)
- return 0;
- if (!strcmp(name, "textContent") || !strcmp(name, "innerText")) {
- const char *text = js_tostring(state, -1);
- unsigned int len = (unsigned int)strlen(text);
- if (br_set_text_content(D, node, text, len) != 0) {
- if (host.status)
- host.status("Page text arena is full", 1);
- } else if (host.changed) {
- host.changed();
- }
- return 1;
- }
- if (!strcmp(name, "nodeValue")) {
- const char *text = js_tostring(state, -1);
- if (br_set_text_node(D, node, text,
- (unsigned int)strlen(text)) == 0 &&
- host.changed)
- host.changed();
- return 1;
- }
- if (!strcmp(name, "id") || !strcmp(name, "className") ||
- !strcmp(name, "href") || !strcmp(name, "src") ||
- !strcmp(name, "value") || !strcmp(name, "type") ||
- !strcmp(name, "name") || !strcmp(name, "alt") ||
- !strcmp(name, "title")) {
- const char *value = js_tostring(state, -1);
- if (!strcmp(name, "value") && host.form_set_value &&
- host.form_set_value(node, value))
- return 1;
- if (!strcmp(name, "className"))
- node_set_string(node, "class", value);
- else
- node_set_string(node, name, value);
- return 1;
- }
- if (!strcmp(name, "selectedIndex")) {
- if (host.form_set_selected)
- host.form_set_selected(node, js_tointeger(state, -1));
- return 1;
- }
- if (!strcmp(name, "checked") || !strcmp(name, "disabled") ||
- !strcmp(name, "selected")) {
- int b = js_toboolean(state, -1);
- if (!strcmp(name, "checked") && host.form_set_checked &&
- host.form_set_checked(node, b))
- return 1;
- if (!strcmp(name, "selected") && host.form_set_selected &&
- host.form_set_selected(node, b ? 1 : 0))
- return 1;
- if (b)
- br_set_attr(D, node, name, "", 0);
- else
- br_remove_attr(D, node, name);
- if (host.changed)
- host.changed();
- return 1;
- }
- if (!strcmp(name, "innerHTML")) {
- const char *html = js_tostring(state, -1);
- char key[32];
- br_set_inner_html(D, node, html, (unsigned int)strlen(html));
- snprintf(key, sizeof(key), "html_%u", node + 1);
- js_pushstring(state, html);
- js_setregistry(state, key);
- if (host.changed)
- host.changed();
- return 1;
- }
- if (!strcmp(name, "outerHTML")) {
- char key[32];
- snprintf(key, sizeof(key), "html_%u", node + 1);
- js_pushstring(state, js_tostring(state, -1));
- js_setregistry(state, key);
- return 1;
- }
- if (!strcmp(name, "style")) {
- if (js_isstring(state, -1))
- node_set_string(node, "style",
- js_tostring(state, -1));
- return 1;
- }
- return 0;
- }
- static int node_delete(js_State *state, void *p, const char *name)
- {
- (void)state;
- (void)p;
- (void)name;
- return 0;
- }
- static void doc_getelementbyid(js_State *state)
- {
- const char *id = js_tostring(state, 1);
- push_node(state, br_find_id(D, id));
- }
- static void console_log(js_State *state)
- {
- int i;
- int n = js_gettop(state);
- for (i = 1; i < n; i++) {
- if (i > 1)
- u_putc(' ');
- u_puts(js_tostring(state, i));
- }
- u_putc('\n');
- }
- static void js_alert(js_State *state)
- {
- char msg[160];
- unsigned int used = 0;
- int i;
- int n = js_gettop(state);
- for (i = 1; i < n; i++) {
- const char *s = js_tostring(state, i);
- unsigned int k;
- if (i > 1 && used + 1 < sizeof(msg))
- msg[used++] = ' ';
- for (k = 0; s[k] && used + 1 < sizeof(msg); k++)
- msg[used++] = s[k];
- }
- msg[used] = '\0';
- if (host.status)
- host.status(msg, 0);
- }
- static void push_query_array(js_State *state, unsigned int root,
- const char *selector)
- {
- unsigned int out[256];
- unsigned int n = br_query_all(D, root, selector, out, 256);
- unsigned int i;
- js_newarray(state);
- for (i = 0; i < n; i++) {
- push_node(state, out[i]);
- js_setindex(state, -2, (int)i);
- }
- }
- static void doc_create_element(js_State *state)
- {
- const char *name = js_tostring(state, 1);
- char lower[32];
- unsigned int i;
- for (i = 0; name[i] && i + 1 < sizeof(lower); i++) {
- char c = name[i];
- if (c >= 'A' && c <= 'Z')
- c = (char)(c - 'A' + 'a');
- lower[i] = c;
- }
- lower[i] = '\0';
- push_node(state, br_create_element(D, lower, i));
- }
- static void doc_create_text(js_State *state)
- {
- const char *text = js_tostring(state, 1);
- push_node(state, br_create_text(D, text, (unsigned int)strlen(text)));
- }
- static void doc_create_comment(js_State *state)
- {
- const char *text = js_tostring(state, 1);
- push_node(state, br_create_comment(D, text, (unsigned int)strlen(text)));
- }
- static void doc_create_fragment(js_State *state)
- {
- push_node(state, br_create_fragment(D));
- }
- static void doc_create_attribute(js_State *state)
- {
- const char *name = js_tostring(state, 1);
- js_newobject(state);
- js_pushstring(state, name);
- js_setproperty(state, -2, "name");
- js_pushstring(state, "");
- js_setproperty(state, -2, "value");
- js_pushboolean(state, 1);
- js_setproperty(state, -2, "specified");
- }
- static void doc_getelementsbytagname(js_State *state)
- {
- push_query_array(state, 0, js_tostring(state, 1));
- }
- static void doc_getelementsbyclassname(js_State *state)
- {
- const char *name = js_tostring(state, 1);
- char sel[256];
- unsigned int n = 0, i = 0;
- while (name[i] && n + 2 < sizeof(sel)) {
- while (name[i] == ' ')
- i++;
- if (!name[i])
- break;
- sel[n++] = '.';
- while (name[i] && name[i] != ' ' && n + 1 < sizeof(sel))
- sel[n++] = name[i++];
- }
- sel[n] = '\0';
- push_query_array(state, 0, sel);
- }
- static void doc_queryselector(js_State *state)
- {
- unsigned int out[1];
- unsigned int n = br_query_all(D, 0, js_tostring(state, 1), out, 1);
- if (n)
- push_node(state, out[0]);
- else
- js_pushnull(state);
- }
- static void doc_queryselectorall(js_State *state)
- {
- push_query_array(state, 0, js_tostring(state, 1));
- }
- static void location_get(js_State *state)
- {
- js_pushstring(state, current_url ? current_url : "");
- }
- static void location_set(js_State *state)
- {
- const char *url = js_tostring(state, 1);
- if (host.navigate)
- host.navigate(url);
- }
- static void win_noop(js_State *state);
- struct loc_parts {
- const char *protocol, *host, *hostname, *port, *path, *search, *hash;
- const char *origin;
- unsigned int protocol_len, host_len, hostname_len, port_len;
- unsigned int path_len, search_len, hash_len, origin_len;
- };
- static void loc_split(const char *u, struct loc_parts *p)
- {
- unsigned int n = (unsigned int)strlen(u), i;
- const char *rest;
- memset(p, 0, sizeof(*p));
- p->path = u;
- p->path_len = n;
- p->origin = "null";
- p->origin_len = 4;
- for (i = 0; i < n; i++)
- if (u[i] == ':')
- break;
- if (i + 2 < n && u[i] == ':' && u[i + 1] == '/' && u[i + 2] == '/') {
- const char *hosts = u + i + 3, *hoste = hosts;
- while (*hoste && *hoste != '/' && *hoste != '?' && *hoste != '#')
- hoste++;
- p->protocol = u;
- p->protocol_len = i + 1;
- p->host = hosts;
- p->host_len = (unsigned int)(hoste - hosts);
- p->hostname = hosts;
- p->hostname_len = p->host_len;
- for (i = 0; i < p->hostname_len; i++)
- if (hosts[i] == ':') {
- p->port = hosts + i + 1;
- p->port_len = p->hostname_len - i - 1;
- p->hostname_len = i;
- break;
- }
- p->origin = u;
- p->origin_len = (unsigned int)(hoste - u);
- rest = hoste;
- } else {
- p->protocol = "file:";
- p->protocol_len = 5;
- rest = u;
- }
- {
- const char *q = rest;
- while (*q && *q != '?' && *q != '#')
- q++;
- p->path = rest;
- p->path_len = (unsigned int)(q - rest);
- if (*q == '?') {
- const char *s = q;
- while (*q && *q != '#')
- q++;
- p->search = s;
- p->search_len = (unsigned int)(q - s);
- }
- if (*q == '#') {
- p->hash = q;
- p->hash_len = (unsigned int)strlen(q);
- }
- }
- }
- static void push_location(js_State *state)
- {
- struct loc_parts p;
- loc_split(current_url ? current_url : "", &p);
- js_newobject(state);
- js_newcfunction(state, location_get, "get href", 0);
- js_newcfunction(state, location_set, "set href", 1);
- js_defaccessor(state, -3, "href", 0);
- #define LOC_FIELD(field) \
- do { \
- js_pushlstring(state, p.field ? p.field : "", \
- p.field ? (int)p.field##_len : 0); \
- js_setproperty(state, -2, #field); \
- } while (0)
- LOC_FIELD(protocol);
- LOC_FIELD(host);
- LOC_FIELD(hostname);
- LOC_FIELD(port);
- js_pushlstring(state, p.path ? p.path : "",
- p.path ? (int)p.path_len : 0);
- js_setproperty(state, -2, "pathname");
- LOC_FIELD(search);
- LOC_FIELD(hash);
- LOC_FIELD(origin);
- #undef LOC_FIELD
- js_newcfunction(state, win_noop, "reload", 0);
- js_setproperty(state, -2, "reload");
- js_newcfunction(state, win_noop, "assign", 1);
- js_setproperty(state, -2, "assign");
- js_newcfunction(state, win_noop, "replace", 1);
- js_setproperty(state, -2, "replace");
- js_newcfunction(state, win_noop, "toString", 0);
- js_setproperty(state, -2, "toString");
- }
- /* ---- URL resolution for <a>/<area> URL properties ---- */
- static int url_has_scheme(const char *s)
- {
- unsigned int i = 1;
- if (!((s[0] >= 'a' && s[0] <= 'z') ||
- (s[0] >= 'A' && s[0] <= 'Z')))
- return 0;
- while (s[i]) {
- char c = s[i];
- if (c == ':')
- return 1;
- if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') || c == '+' || c == '-' ||
- c == '.'))
- return 0;
- i++;
- }
- return 0;
- }
- static void url_put(char *out, unsigned int cap, unsigned int *n,
- const char *s, unsigned int len)
- {
- unsigned int i;
- for (i = 0; i < len && *n + 1 < cap; i++)
- out[(*n)++] = s[i];
- }
- /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
- static void url_normalize(char *url)
- {
- char tmp[512];
- char *path;
- unsigned int n = 0, i = 0;
- path = strstr(url, "://");
- if (path) {
- path += 3;
- while (*path && *path != '/')
- path++;
- } else {
- path = url;
- }
- if (path[0] != '/')
- return;
- while (path[i]) {
- unsigned int start;
- while (path[i] == '/')
- i++;
- start = i;
- while (path[i] && path[i] != '/')
- i++;
- if (i == start)
- continue;
- if (i - start == 1 && path[start] == '.')
- continue;
- if (i - start == 2 && path[start] == '.' &&
- path[start + 1] == '.') {
- while (n > 0 && tmp[n - 1] != '/')
- n--;
- if (n > 0)
- n--;
- continue;
- }
- if (n + 1 < sizeof(tmp))
- tmp[n++] = '/';
- while (start < i && n + 1 < sizeof(tmp))
- tmp[n++] = path[start++];
- }
- if (n == 0)
- tmp[n++] = '/';
- tmp[n] = '\0';
- memcpy(path, tmp, n + 1);
- }
- static void url_resolve(const char *base, const char *rel,
- char *out, unsigned int cap)
- {
- struct loc_parts bp;
- unsigned int n = 0, i;
- if (cap == 0)
- return;
- if (!rel[0]) {
- url_put(out, cap, &n, base, (unsigned int)strlen(base));
- out[n] = '\0';
- return;
- }
- if (url_has_scheme(rel)) {
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- out[n] = '\0';
- url_normalize(out);
- return;
- }
- loc_split(base, &bp);
- if (rel[0] == '/' && rel[1] == '/') {
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- } else if (rel[0] == '/') {
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- url_put(out, cap, &n, "//", 2);
- url_put(out, cap, &n, bp.host, bp.host_len);
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- } else if (rel[0] == '#' || rel[0] == '?') {
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- if (bp.host_len || (bp.protocol_len == 5 &&
- bp.protocol[0] == 'f')) {
- url_put(out, cap, &n, "//", 2);
- url_put(out, cap, &n, bp.host, bp.host_len);
- }
- url_put(out, cap, &n, bp.path, bp.path_len);
- if (rel[0] == '#')
- url_put(out, cap, &n, bp.search, bp.search_len);
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- } else {
- const char *dir_end = bp.path;
- for (i = 0; i < bp.path_len; i++)
- if (bp.path[i] == '/')
- dir_end = bp.path + i + 1;
- if (dir_end == bp.path)
- dir_end = bp.path + bp.path_len;
- url_put(out, cap, &n, bp.protocol, bp.protocol_len);
- if (bp.host_len || (bp.protocol_len == 5 &&
- bp.protocol[0] == 'f')) {
- url_put(out, cap, &n, "//", 2);
- url_put(out, cap, &n, bp.host, bp.host_len);
- }
- url_put(out, cap, &n, bp.path,
- (unsigned int)(dir_end - bp.path));
- url_put(out, cap, &n, rel, (unsigned int)strlen(rel));
- }
- out[n] = '\0';
- url_normalize(out);
- }
- /* <a> URL properties are resolved against the page URL, like the DOM. */
- static void push_element_url(js_State *state, unsigned int node,
- const char *name)
- {
- char abs_url[512];
- const char *href = br_find_attr(D, node, "href");
- struct loc_parts p;
- if (!href || !href[0]) {
- js_pushstring(state, "");
- return;
- }
- url_resolve(current_url ? current_url : "/", href,
- abs_url, sizeof(abs_url));
- loc_split(abs_url, &p);
- if (!strcmp(name, "href"))
- js_pushstring(state, abs_url);
- else if (!strcmp(name, "protocol"))
- js_pushlstring(state, p.protocol, (int)p.protocol_len);
- else if (!strcmp(name, "origin"))
- js_pushlstring(state, p.origin ? p.origin : "",
- (int)p.origin_len);
- else if (!strcmp(name, "host"))
- js_pushlstring(state, p.host ? p.host : "", (int)p.host_len);
- else if (!strcmp(name, "hostname"))
- js_pushlstring(state, p.hostname ? p.hostname : "",
- (int)p.hostname_len);
- else if (!strcmp(name, "port"))
- js_pushlstring(state, p.port ? p.port : "", (int)p.port_len);
- else if (!strcmp(name, "pathname"))
- js_pushlstring(state, p.path ? p.path : "", (int)p.path_len);
- else if (!strcmp(name, "search"))
- js_pushlstring(state, p.search ? p.search : "",
- (int)p.search_len);
- else
- js_pushlstring(state, p.hash ? p.hash : "", (int)p.hash_len);
- }
- static void win_noop(js_State *state)
- {
- (void)state;
- }
- static void timer_add(js_State *state, int repeat)
- {
- int i;
- unsigned int ms;
- if (!js_iscallable(state, 1)) {
- js_pushnumber(state, 0);
- return;
- }
- ms = js_isdefined(state, 2) ?
- (unsigned int)js_tointeger(state, 2) : 0;
- if (repeat && ms == 0)
- ms = 1;
- for (i = 0; i < JS_TIMERS; i++)
- if (!timers[i].used)
- break;
- if (i == JS_TIMERS) {
- js_pushnumber(state, 0);
- return;
- }
- js_copy(state, 1);
- snprintf(timers[i].ref, sizeof(timers[i].ref), "%s",
- js_ref(state));
- timers[i].used = 1;
- timers[i].repeat = repeat;
- timers[i].interval = ms;
- timers[i].deadline = u_ticks_ms() + ms;
- js_pushnumber(state, i + 1);
- }
- static void win_settimeout(js_State *state)
- {
- timer_add(state, 0);
- }
- static void win_setinterval(js_State *state)
- {
- timer_add(state, 1);
- }
- static void timer_clear(js_State *state)
- {
- int id = js_tointeger(state, 1);
- if (id >= 1 && id <= JS_TIMERS && timers[id - 1].used) {
- js_unref(state, timers[id - 1].ref);
- timers[id - 1].used = 0;
- }
- }
- static void win_requestanimationframe(js_State *state)
- {
- timer_add(state, 0);
- }
- static void win_performance_now(js_State *state)
- {
- js_pushnumber(state, (double)u_ticks_ms());
- }
- struct computed_prop {
- const char *js;
- const char *css;
- };
- static const struct computed_prop computed_props[] = {
- { "display", "display" }, { "position", "position" },
- { "width", "width" }, { "height", "height" },
- { "color", "color" }, { "backgroundColor", "background-color" },
- { "fill", "fill" }, { "stroke", "stroke" },
- { "fontSize", "font-size" }, { "fontWeight", "font-weight" },
- { "fontStyle", "font-style" }, { "fontFamily", "font-family" },
- { "textAlign", "text-align" }, { "float", "float" },
- { "cssFloat", "float" }, { "clear", "clear" },
- { "opacity", "opacity" }, { "visibility", "visibility" },
- { "overflow", "overflow" }, { "whiteSpace", "white-space" },
- { "textTransform", "text-transform" }, { "boxSizing", "box-sizing" },
- { "lineHeight", "line-height" }, { "zIndex", "z-index" },
- { "top", "top" }, { "left", "left" }, { "right", "right" },
- { "bottom", "bottom" },
- { "marginTop", "margin-top" }, { "marginRight", "margin-right" },
- { "marginBottom", "margin-bottom" }, { "marginLeft", "margin-left" },
- { "paddingTop", "padding-top" }, { "paddingRight", "padding-right" },
- { "paddingBottom", "padding-bottom" },
- { "paddingLeft", "padding-left" },
- { "borderTopWidth", "border-top-width" },
- { "borderRightWidth", "border-right-width" },
- { "borderBottomWidth", "border-bottom-width" },
- { "borderLeftWidth", "border-left-width" },
- { "borderTopColor", "border-top-color" },
- { "borderRightColor", "border-right-color" },
- { "borderBottomColor", "border-bottom-color" },
- { "borderLeftColor", "border-left-color" },
- { "backgroundImage", "background-image" },
- { "backgroundRepeat", "background-repeat" },
- { "backgroundPosition", "background-position" },
- { "backgroundSize", "background-size" },
- { "transform", "transform" },
- { 0, 0 }
- };
- static void computed_get(js_State *state)
- {
- unsigned int node = node_of(js_currentfunctiondata(state));
- const char *prop = js_tostring(state, 1);
- char buf[192];
- if (host.computed && host.computed(node, prop, buf, sizeof(buf)))
- js_pushstring(state, buf);
- else
- js_pushstring(state, "");
- }
- static void win_getcomputedstyle(js_State *state)
- {
- unsigned int node = 0;
- char buf[192];
- int i;
- if (js_isuserdata(state, 1, "node"))
- node = node_of(js_touserdata(state, 1, "node"));
- js_newobject(state);
- def_func_data(state, "getPropertyValue", computed_get, 1, node + 1);
- for (i = 0; computed_props[i].js; i++) {
- if (!host.computed ||
- !host.computed(node, computed_props[i].css, buf,
- sizeof(buf)))
- continue;
- js_pushstring(state, buf);
- js_setproperty(state, -2, computed_props[i].js);
- }
- js_pushstring(state, "");
- js_setproperty(state, -2, "cssText");
- }
- static void win_matchmedia(js_State *state)
- {
- const char *query = js_tostring(state, 1);
- js_newobject(state);
- js_pushboolean(state, 0);
- js_setproperty(state, -2, "matches");
- js_pushstring(state, query);
- js_setproperty(state, -2, "media");
- def_func(state, "addListener", win_noop, 1);
- def_func(state, "removeListener", win_noop, 1);
- def_func(state, "addEventListener", win_noop, 2);
- def_func(state, "removeEventListener", win_noop, 2);
- }
- static void install_globals(js_State *state)
- {
- unsigned int h;
- /* Shared prototype of the node/style/dataset wrappers. */
- js_newobject(state);
- js_setregistry(state, "wrapproto");
- js_newobject(state);
- def_func(state, "getElementById", doc_getelementbyid, 1);
- def_func(state, "createElement", doc_create_element, 1);
- def_func(state, "createTextNode", doc_create_text, 1);
- def_func(state, "createComment", doc_create_comment, 1);
- def_func(state, "createDocumentFragment", doc_create_fragment, 0);
- def_func(state, "createAttribute", doc_create_attribute, 1);
- def_func(state, "getElementsByTagName", doc_getelementsbytagname, 1);
- def_func(state, "getElementsByClassName", doc_getelementsbyclassname, 1);
- def_func(state, "querySelector", doc_queryselector, 1);
- def_func(state, "querySelectorAll", doc_queryselectorall, 1);
- def_func(state, "addEventListener", doc_addlistener, 2);
- def_func(state, "removeEventListener", doc_removelistener, 2);
- def_func(state, "createEvent", doc_createevent, 1);
- h = br_find_tag(D, BR_TAG_HTML);
- if (!h && D->nnode > 1)
- h = D->nodes[0].first ? D->nodes[0].first + 1 : 0;
- push_node(state, h);
- js_setproperty(state, -2, "documentElement");
- h = br_find_tag(D, BR_TAG_BODY);
- push_node(state, h);
- js_setproperty(state, -2, "body");
- h = br_find_tag(D, BR_TAG_HEAD);
- push_node(state, h);
- js_setproperty(state, -2, "head");
- js_pushnumber(state, 9);
- js_setproperty(state, -2, "nodeType");
- js_pushstring(state, "#document");
- js_setproperty(state, -2, "nodeName");
- js_pushnull(state);
- js_setproperty(state, -2, "ownerDocument");
- js_pushstring(state, "CSS1Compat");
- js_setproperty(state, -2, "compatMode");
- js_pushstring(state, D->title);
- js_setproperty(state, -2, "title");
- js_pushstring(state, "complete");
- js_setproperty(state, -2, "readyState");
- js_pushstring(state, "");
- js_setproperty(state, -2, "cookie");
- js_pushstring(state, current_url ? current_url : "");
- js_setproperty(state, -2, "URL");
- js_defglobal(state, "document", JS_DONTENUM);
- js_newobject(state);
- js_newcfunction(state, console_log, "log", 0);
- js_setproperty(state, -2, "log");
- js_defglobal(state, "console", JS_DONTENUM);
- js_newcfunction(state, js_alert, "alert", 1);
- js_defglobal(state, "alert", JS_DONTENUM);
- js_newcfunction(state, event_call, "Event", 1);
- js_defglobal(state, "Event", JS_DONTENUM);
- js_newcfunction(state, custom_event_call, "CustomEvent", 1);
- js_defglobal(state, "CustomEvent", JS_DONTENUM);
- js_newcfunction(state, mouse_event_call, "MouseEvent", 1);
- js_defglobal(state, "MouseEvent", JS_DONTENUM);
- push_location(state);
- js_defglobal(state, "location", JS_DONTENUM);
- js_newobject(state);
- js_pushstring(state, "Mozilla/5.0 (X11; Linux i686) NebOS/0.2");
- js_setproperty(state, -2, "userAgent");
- js_pushstring(state, "NebOS");
- js_setproperty(state, -2, "platform");
- js_pushstring(state, "en-US");
- js_setproperty(state, -2, "language");
- js_defglobal(state, "navigator", JS_DONTENUM);
- js_newobject(state);
- js_pushnumber(state, 1);
- js_setproperty(state, -2, "length");
- def_func(state, "pushState", win_noop, 3);
- def_func(state, "replaceState", win_noop, 3);
- def_func(state, "back", win_noop, 0);
- def_func(state, "forward", win_noop, 0);
- def_func(state, "go", win_noop, 1);
- js_defglobal(state, "history", JS_DONTENUM);
- def_global_func(state, "matchMedia", win_matchmedia, 1);
- def_global_func(state, "getComputedStyle", win_getcomputedstyle, 1);
- def_global_func(state, "addEventListener", win_addlistener, 2);
- def_global_func(state, "removeEventListener", win_removelistener, 2);
- def_global_func(state, "scrollTo", win_noop, 2);
- def_global_func(state, "scrollBy", win_noop, 2);
- def_global_func(state, "setTimeout", win_settimeout, 1);
- def_global_func(state, "setInterval", win_setinterval, 1);
- def_global_func(state, "clearTimeout", timer_clear, 1);
- def_global_func(state, "clearInterval", timer_clear, 1);
- def_global_func(state, "requestAnimationFrame", win_requestanimationframe, 1);
- def_global_func(state, "cancelAnimationFrame", timer_clear, 1);
- js_newobject(state);
- def_func(state, "now", win_performance_now, 0);
- js_newobject(state);
- js_setproperty(state, -2, "timing");
- js_defglobal(state, "performance", JS_DONTENUM);
- js_pushnumber(state, host.width ? (int)host.width : 1024);
- js_defglobal(state, "innerWidth", JS_DONTENUM);
- js_pushnumber(state, host.height ? (int)host.height : 768);
- js_defglobal(state, "innerHeight", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "pageXOffset", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "pageYOffset", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "scrollX", JS_DONTENUM);
- js_pushnumber(state, 0);
- js_defglobal(state, "scrollY", JS_DONTENUM);
- js_pushnumber(state, 1);
- js_defglobal(state, "devicePixelRatio", JS_DONTENUM);
- js_pushglobal(state);
- js_defglobal(state, "window", JS_DONTENUM);
- js_pushglobal(state);
- js_defglobal(state, "globalThis", JS_DONTENUM);
- js_getglobal(state, "document");
- js_getglobal(state, "location");
- js_setproperty(state, -2, "location");
- js_pop(state, 1);
- js_getglobal(state, "document");
- js_pushglobal(state);
- js_setproperty(state, -2, "defaultView");
- js_pop(state, 1);
- }
- int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
- {
- if (!doc || !h)
- return -1;
- D = doc;
- host = *h;
- current_url = h->page_url;
- panic_armed = 0;
- memset(timers, 0, sizeof(timers));
- memset(listeners, 0, sizeof(listeners));
- memset(events, 0, sizeof(events));
- memset(event_templates, 0, sizeof(event_templates));
- /* Classic scripts are sloppy by default in browsers; strict mode is
- * opt-in via a "use strict" directive. */
- J = js_newstate(0, 0, 0);
- if (!J)
- return -1;
- js_setreport(J, report_cb);
- js_atpanic(J, panic_cb);
- install_globals(J);
- return 0;
- }
- void js_browser_stop(void)
- {
- if (J)
- js_freestate(J);
- J = 0;
- D = 0;
- current_url = 0;
- panic_armed = 0;
- memset(timers, 0, sizeof(timers));
- }
- int js_browser_active(void)
- {
- return J != 0;
- }
- static void report_top(js_State *state)
- {
- const char *msg;
- js_getproperty(state, -1, "stack");
- if (js_isstring(state, -1)) {
- /* QuickJS's stack is only the frames: lead with
- * "Name: message" like the MuJS reports did. */
- char buf[768];
- const char *head = js_trystring(state, -2, "JavaScript error");
- snprintf(buf, sizeof(buf), "%s\n%s", head,
- js_tostring(state, -1));
- msg = buf;
- if (host.report)
- host.report(msg);
- js_pop(state, 1);
- } else {
- js_pop(state, 1);
- msg = js_trystring(state, -1, "JavaScript error");
- if (host.report)
- host.report(msg);
- }
- js_pop(state, 1);
- }
- void js_browser_tick(void)
- {
- unsigned int now;
- int i, ran = 0;
- if (!J)
- return;
- now = u_ticks_ms();
- for (i = 0; i < JS_TIMERS; i++) {
- if (!timers[i].used ||
- (int)(now - timers[i].deadline) < 0)
- continue;
- js_setlimit(J, JS_RUN_LIMIT, 0);
- js_getregistry(J, timers[i].ref);
- if (!js_iscallable(J, -1)) {
- js_pop(J, 1);
- js_unref(J, timers[i].ref);
- timers[i].used = 0;
- continue;
- }
- js_pushundefined(J);
- if (js_pcall(J, 0))
- report_top(J);
- else
- js_pop(J, 1);
- if (timers[i].used) {
- if (timers[i].repeat)
- timers[i].deadline = now + timers[i].interval;
- else {
- js_unref(J, timers[i].ref);
- timers[i].used = 0;
- }
- }
- if (++ran >= 4)
- break;
- }
- js_runjobs(J);
- }
- int js_browser_run(const char *source, const char *url)
- {
- int r;
- if (!J || !D)
- return -1;
- js_setlimit(J, JS_RUN_LIMIT, 0);
- panic_armed = 1;
- if (setjmp(panic_env)) {
- panic_armed = 0;
- if (host.report)
- host.report("uncaught JavaScript exception");
- /* The try/exception stack is unusable after a panic. Leak the
- * state; the page heap reset on navigation reclaims it. */
- J = 0;
- D = 0;
- return -1;
- }
- if (js_ploadstring(J, url ? url : "[inline]", source)) {
- report_top(J);
- panic_armed = 0;
- return -1;
- }
- js_pushundefined(J);
- r = js_pcall(J, 0);
- if (r) {
- report_top(J);
- panic_armed = 0;
- return -1;
- }
- js_pop(J, 1);
- js_runjobs(J);
- panic_armed = 0;
- return 0;
- }
|