wasmthreadcontroller.js 217 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271
  1. var pas = { $libimports: {}};
  2. var rtl = {
  3. version: 30101,
  4. quiet: false,
  5. debug_load_units: false,
  6. debug_rtti: false,
  7. $res : {},
  8. debug: function(){
  9. if (rtl.quiet || !console || !console.log) return;
  10. console.log(arguments);
  11. },
  12. error: function(s){
  13. rtl.debug('Error: ',s);
  14. throw s;
  15. },
  16. warn: function(s){
  17. rtl.debug('Warn: ',s);
  18. },
  19. checkVersion: function(v){
  20. if (rtl.version != v) throw "expected rtl version "+v+", but found "+rtl.version;
  21. },
  22. hiInt: Math.pow(2,53),
  23. hasString: function(s){
  24. return rtl.isString(s) && (s.length>0);
  25. },
  26. isArray: function(a) {
  27. return Array.isArray(a);
  28. },
  29. isFunction: function(f){
  30. return typeof(f)==="function";
  31. },
  32. isModule: function(m){
  33. return rtl.isObject(m) && rtl.hasString(m.$name) && (pas[m.$name]===m);
  34. },
  35. isImplementation: function(m){
  36. return rtl.isObject(m) && rtl.isModule(m.$module) && (m.$module.$impl===m);
  37. },
  38. isNumber: function(n){
  39. return typeof(n)==="number";
  40. },
  41. isObject: function(o){
  42. var s=typeof(o);
  43. return (typeof(o)==="object") && (o!=null);
  44. },
  45. isString: function(s){
  46. return typeof(s)==="string";
  47. },
  48. getNumber: function(n){
  49. return typeof(n)==="number"?n:NaN;
  50. },
  51. getChar: function(c){
  52. return ((typeof(c)==="string") && (c.length===1)) ? c : "";
  53. },
  54. getObject: function(o){
  55. return ((typeof(o)==="object") || (typeof(o)==='function')) ? o : null;
  56. },
  57. isTRecord: function(type){
  58. return (rtl.isObject(type) && type.hasOwnProperty('$new') && (typeof(type.$new)==='function'));
  59. },
  60. isPasClass: function(type){
  61. return (rtl.isObject(type) && type.hasOwnProperty('$classname') && rtl.isObject(type.$module));
  62. },
  63. isPasClassInstance: function(type){
  64. return (rtl.isObject(type) && rtl.isPasClass(type.$class));
  65. },
  66. hexStr: function(n,digits){
  67. return ("000000000000000"+n.toString(16).toUpperCase()).slice(-digits);
  68. },
  69. m_loading: 0,
  70. m_loading_intf: 1,
  71. m_intf_loaded: 2,
  72. m_loading_impl: 3, // loading all used unit
  73. m_initializing: 4, // running initialization
  74. m_initialized: 5,
  75. module: function(module_name, intfuseslist, intfcode, impluseslist){
  76. if (rtl.debug_load_units) rtl.debug('rtl.module name="'+module_name+'" intfuses='+intfuseslist+' impluses='+impluseslist);
  77. if (!rtl.hasString(module_name)) rtl.error('invalid module name "'+module_name+'"');
  78. if (!rtl.isArray(intfuseslist)) rtl.error('invalid interface useslist of "'+module_name+'"');
  79. if (!rtl.isFunction(intfcode)) rtl.error('invalid interface code of "'+module_name+'"');
  80. if (!(impluseslist==undefined) && !rtl.isArray(impluseslist)) rtl.error('invalid implementation useslist of "'+module_name+'"');
  81. if (pas[module_name])
  82. rtl.error('module "'+module_name+'" is already registered');
  83. var r = Object.create(rtl.tSectionRTTI);
  84. var module = r.$module = pas[module_name] = {
  85. $name: module_name,
  86. $intfuseslist: intfuseslist,
  87. $impluseslist: impluseslist,
  88. $state: rtl.m_loading,
  89. $intfcode: intfcode,
  90. $implcode: null,
  91. $impl: null,
  92. $rtti: r
  93. };
  94. if (impluseslist) module.$impl = {
  95. $module: module,
  96. $rtti: r
  97. };
  98. },
  99. exitcode: 0,
  100. run: function(module_name){
  101. try {
  102. if (!rtl.hasString(module_name)) module_name='program';
  103. if (rtl.debug_load_units) rtl.debug('rtl.run module="'+module_name+'"');
  104. rtl.initRTTI();
  105. var module = pas[module_name];
  106. if (!module) rtl.error('rtl.run module "'+module_name+'" missing');
  107. rtl.loadintf(module);
  108. rtl.loadimpl(module);
  109. if ((module_name=='program') || (module_name=='library')){
  110. if (rtl.debug_load_units) rtl.debug('running $main');
  111. var r = pas[module_name].$main();
  112. if (rtl.isNumber(r)) rtl.exitcode = r;
  113. }
  114. } catch(re) {
  115. if (!rtl.showUncaughtExceptions) {
  116. throw re
  117. } else {
  118. if (!rtl.handleUncaughtException(re)) {
  119. rtl.showException(re);
  120. rtl.exitcode = 216;
  121. }
  122. }
  123. }
  124. return rtl.exitcode;
  125. },
  126. showException : function (re) {
  127. var errStack="";
  128. if (rtl.isObject(re) && re.hasOwnProperty('FJSError') && rtl.isObject(re.FJSError) && !(re.FJSError.stack==undefined)) // rtl Exception
  129. errStack=re.FJSError.stack
  130. else if (rtl.isObject(re) && re.hasOwnProperty('stack') && !(re.stack==undefined)) // native JS Error
  131. errStack=re.stack
  132. else
  133. errStack=re; // unknown object
  134. var errMsg = rtl.hasString(re.$classname) ? re.$classname : '';
  135. errMsg += ((errMsg) ? ': ' : '') + (re.hasOwnProperty('fMessage') ? re.fMessage : '');
  136. errMsg += ((errMsg) ? "\n" : '') + errStack;
  137. errMsg = "Uncaught Exception:\n" + errMsg;
  138. console.log(errMsg);
  139. alert(errMsg);
  140. },
  141. handleUncaughtException: function (e) {
  142. if (rtl.onUncaughtException) {
  143. try {
  144. rtl.onUncaughtException(e);
  145. return true;
  146. } catch (ee) {
  147. return false;
  148. }
  149. } else {
  150. return false;
  151. }
  152. },
  153. loadintf: function(module){
  154. if (module.$state>rtl.m_loading_intf) return; // already finished
  155. if (rtl.debug_load_units) rtl.debug('loadintf: "'+module.$name+'"');
  156. if (module.$state===rtl.m_loading_intf)
  157. rtl.error('unit cycle detected "'+module.$name+'"');
  158. module.$state=rtl.m_loading_intf;
  159. // load interfaces of interface useslist
  160. rtl.loaduseslist(module,module.$intfuseslist,rtl.loadintf);
  161. // run interface
  162. if (rtl.debug_load_units) rtl.debug('loadintf: run intf of "'+module.$name+'"');
  163. module.$intfcode(module.$intfuseslist);
  164. // success
  165. module.$state=rtl.m_intf_loaded;
  166. // Note: units only used in implementations are not yet loaded (not even their interfaces)
  167. },
  168. loaduseslist: function(module,useslist,f){
  169. if (useslist==undefined) return;
  170. var len = useslist.length;
  171. for (var i = 0; i<len; i++) {
  172. var unitname=useslist[i];
  173. if (rtl.debug_load_units) rtl.debug('loaduseslist of "'+module.$name+'" uses="'+unitname+'"');
  174. if (pas[unitname]==undefined)
  175. rtl.error('module "'+module.$name+'" misses "'+unitname+'"');
  176. f(pas[unitname]);
  177. }
  178. },
  179. loadimpl: function(module){
  180. if (module.$state>=rtl.m_loading_impl) return; // already processing
  181. if (module.$state<rtl.m_intf_loaded) rtl.error('loadimpl: interface not loaded of "'+module.$name+'"');
  182. if (rtl.debug_load_units) rtl.debug('loadimpl: load uses of "'+module.$name+'"');
  183. module.$state=rtl.m_loading_impl;
  184. // load interfaces of implementation useslist
  185. rtl.loaduseslist(module,module.$impluseslist,rtl.loadintf);
  186. // load implementation of interfaces useslist
  187. rtl.loaduseslist(module,module.$intfuseslist,rtl.loadimpl);
  188. // load implementation of implementation useslist
  189. rtl.loaduseslist(module,module.$impluseslist,rtl.loadimpl);
  190. // Note: At this point all interfaces used by this unit are loaded. If
  191. // there are implementation uses cycles some used units might not yet be
  192. // initialized. This is by design.
  193. // run implementation
  194. if (rtl.debug_load_units) rtl.debug('loadimpl: run impl of "'+module.$name+'"');
  195. if (rtl.isFunction(module.$implcode)) module.$implcode(module.$impluseslist);
  196. // run initialization
  197. if (rtl.debug_load_units) rtl.debug('loadimpl: run init of "'+module.$name+'"');
  198. module.$state=rtl.m_initializing;
  199. if (rtl.isFunction(module.$init)) module.$init();
  200. // unit initialized
  201. module.$state=rtl.m_initialized;
  202. },
  203. createCallback: function(scope, fn){
  204. var cb;
  205. if (typeof(fn)==='string'){
  206. if (!scope.hasOwnProperty('$events')) scope.$events = {};
  207. cb = scope.$events[fn];
  208. if (cb) return cb;
  209. scope.$events[fn] = cb = function(){
  210. return scope[fn].apply(scope,arguments);
  211. };
  212. } else {
  213. cb = function(){
  214. return fn.apply(scope,arguments);
  215. };
  216. };
  217. cb.scope = scope;
  218. cb.fn = fn;
  219. return cb;
  220. },
  221. createSafeCallback: function(scope, fn){
  222. var cb;
  223. if (typeof(fn)==='string'){
  224. if (!scope[fn]) return null;
  225. if (!scope.hasOwnProperty('$events')) scope.$events = {};
  226. cb = scope.$events[fn];
  227. if (cb) return cb;
  228. scope.$events[fn] = cb = function(){
  229. try{
  230. return scope[fn].apply(scope,arguments);
  231. } catch (err) {
  232. if (!rtl.handleUncaughtException(err)) throw err;
  233. }
  234. };
  235. } else if(!fn) {
  236. return null;
  237. } else {
  238. cb = function(){
  239. try{
  240. return fn.apply(scope,arguments);
  241. } catch (err) {
  242. if (!rtl.handleUncaughtException(err)) throw err;
  243. }
  244. };
  245. };
  246. cb.scope = scope;
  247. cb.fn = fn;
  248. return cb;
  249. },
  250. eqCallback: function(a,b){
  251. // can be a function or a function wrapper
  252. if (a===b){
  253. return true;
  254. } else {
  255. return (a!=null) && (b!=null) && (a.fn) && (a.scope===b.scope) && (a.fn===b.fn);
  256. }
  257. },
  258. initStruct: function(c,parent,name){
  259. if ((parent.$module) && (parent.$module.$impl===parent)) parent=parent.$module;
  260. c.$parent = parent;
  261. if (rtl.isModule(parent)){
  262. c.$module = parent;
  263. c.$name = name;
  264. } else {
  265. c.$module = parent.$module;
  266. c.$name = parent.$name+'.'+name;
  267. };
  268. return parent;
  269. },
  270. initClass: function(c,parent,name,initfn,rttiname){
  271. parent[name] = c;
  272. c.$class = c; // Note: o.$class === Object.getPrototypeOf(o)
  273. c.$classname = rttiname?rttiname:name;
  274. parent = rtl.initStruct(c,parent,name);
  275. c.$fullname = parent.$name+'.'+name;
  276. // rtti
  277. if (rtl.debug_rtti) rtl.debug('initClass '+c.$fullname);
  278. var t = c.$module.$rtti.$Class(c.$classname,{ "class": c });
  279. c.$rtti = t;
  280. if (rtl.isObject(c.$ancestor)) t.ancestor = c.$ancestor.$rtti;
  281. if (!t.ancestor) t.ancestor = null;
  282. // init members
  283. initfn.call(c);
  284. },
  285. createClass: function(parent,name,ancestor,initfn,rttiname){
  286. // create a normal class,
  287. // ancestor must be null or a normal class,
  288. // the root ancestor can be an external class
  289. var c = null;
  290. if (ancestor != null){
  291. c = Object.create(ancestor);
  292. c.$ancestor = ancestor;
  293. // Note:
  294. // if root is an "object" then c.$ancestor === Object.getPrototypeOf(c)
  295. // if root is a "function" then c.$ancestor === c.__proto__, Object.getPrototypeOf(c) returns the root
  296. } else {
  297. c = { $ancestor: null };
  298. c.$create = function(fn,args){
  299. if (args == undefined) args = [];
  300. var o = Object.create(this);
  301. o.$init();
  302. try{
  303. if (typeof(fn)==="string"){
  304. o[fn].apply(o,args);
  305. } else {
  306. fn.apply(o,args);
  307. };
  308. o.AfterConstruction();
  309. } catch($e){
  310. // do not call BeforeDestruction
  311. if (o.Destroy) o.Destroy();
  312. o.$final();
  313. throw $e;
  314. }
  315. return o;
  316. };
  317. c.$destroy = function(fnname){
  318. this.BeforeDestruction();
  319. if (this[fnname]) this[fnname]();
  320. this.$final();
  321. };
  322. };
  323. rtl.initClass(c,parent,name,initfn,rttiname);
  324. },
  325. createClassExt: function(parent,name,ancestor,newinstancefnname,initfn,rttiname){
  326. // Create a class using an external ancestor.
  327. // If newinstancefnname is given, use that function to create the new object.
  328. // If exist call BeforeDestruction and AfterConstruction.
  329. var isFunc = rtl.isFunction(ancestor);
  330. var c = null;
  331. if (isFunc){
  332. // create pascal class descendent from JS function
  333. c = Object.create(ancestor.prototype);
  334. c.$ancestorfunc = ancestor;
  335. c.$ancestor = null; // no pascal ancestor
  336. } else if (ancestor.$func){
  337. // create pascal class descendent from a pascal class descendent of a JS function
  338. isFunc = true;
  339. c = Object.create(ancestor);
  340. c.$ancestor = ancestor;
  341. } else {
  342. c = Object.create(ancestor);
  343. c.$ancestor = null; // no pascal ancestor
  344. }
  345. c.$create = function(fn,args){
  346. if (args == undefined) args = [];
  347. var o = null;
  348. if (newinstancefnname.length>0){
  349. o = this[newinstancefnname](fn,args);
  350. } else if(isFunc) {
  351. o = new this.$func(args);
  352. } else {
  353. o = Object.create(c);
  354. }
  355. if (o.$init) o.$init();
  356. try{
  357. if (typeof(fn)==="string"){
  358. this[fn].apply(o,args);
  359. } else {
  360. fn.apply(o,args);
  361. };
  362. if (o.AfterConstruction) o.AfterConstruction();
  363. } catch($e){
  364. // do not call BeforeDestruction
  365. if (o.Destroy) o.Destroy();
  366. if (o.$final) o.$final();
  367. throw $e;
  368. }
  369. return o;
  370. };
  371. c.$destroy = function(fnname){
  372. if (this.BeforeDestruction) this.BeforeDestruction();
  373. if (this[fnname]) this[fnname]();
  374. if (this.$final) this.$final();
  375. };
  376. rtl.initClass(c,parent,name,initfn,rttiname);
  377. if (isFunc){
  378. function f(){}
  379. f.prototype = c;
  380. c.$func = f;
  381. }
  382. },
  383. createHelper: function(parent,name,ancestor,initfn,rttiname){
  384. // create a helper,
  385. // ancestor must be null or a helper,
  386. var c = null;
  387. if (ancestor != null){
  388. c = Object.create(ancestor);
  389. c.$ancestor = ancestor;
  390. // c.$ancestor === Object.getPrototypeOf(c)
  391. } else {
  392. c = { $ancestor: null };
  393. };
  394. parent[name] = c;
  395. c.$class = c; // Note: o.$class === Object.getPrototypeOf(o)
  396. c.$classname = rttiname?rttiname:name;
  397. parent = rtl.initStruct(c,parent,name);
  398. c.$fullname = parent.$name+'.'+name;
  399. // rtti
  400. var t = c.$module.$rtti.$Helper(c.$classname,{ "helper": c });
  401. c.$rtti = t;
  402. if (rtl.isObject(ancestor)) t.ancestor = ancestor.$rtti;
  403. if (!t.ancestor) t.ancestor = null;
  404. // init members
  405. initfn.call(c);
  406. },
  407. tObjectDestroy: "Destroy",
  408. free: function(obj,name){
  409. if (obj[name]==null) return null;
  410. obj[name].$destroy(rtl.tObjectDestroy);
  411. obj[name]=null;
  412. },
  413. freeLoc: function(obj){
  414. if (obj==null) return null;
  415. obj.$destroy(rtl.tObjectDestroy);
  416. return null;
  417. },
  418. hideProp: function(o,p,v){
  419. Object.defineProperty(o,p, {
  420. enumerable: false,
  421. configurable: true,
  422. writable: true
  423. });
  424. if(arguments.length>2){ o[p]=v; }
  425. },
  426. recNewT: function(parent,name,initfn,full){
  427. // create new record type
  428. var t = {};
  429. if (parent) parent[name] = t;
  430. var h = rtl.hideProp;
  431. if (full){
  432. rtl.initStruct(t,parent,name);
  433. t.$record = t;
  434. h(t,'$record');
  435. h(t,'$name');
  436. h(t,'$parent');
  437. h(t,'$module');
  438. h(t,'$initSpec');
  439. }
  440. initfn.call(t);
  441. if (!t.$new){
  442. t.$new = function(){ return Object.create(t); };
  443. }
  444. t.$clone = function(r){ return t.$new().$assign(r); };
  445. h(t,'$new');
  446. h(t,'$clone');
  447. h(t,'$eq');
  448. h(t,'$assign');
  449. return t;
  450. },
  451. is: function(instance,type){
  452. return type.isPrototypeOf(instance) || (instance===type);
  453. },
  454. isExt: function(instance,type,mode){
  455. // mode===1 means instance must be a Pascal class instance
  456. // mode===2 means instance must be a Pascal class
  457. // Notes:
  458. // isPrototypeOf and instanceof return false on equal
  459. // isPrototypeOf does not work for Date.isPrototypeOf(new Date())
  460. // so if isPrototypeOf is false test with instanceof
  461. // instanceof needs a function on right side
  462. if (instance == null) return false; // Note: ==null checks for undefined too
  463. if ((typeof(type) !== 'object') && (typeof(type) !== 'function')) return false;
  464. if (instance === type){
  465. if (mode===1) return false;
  466. if (mode===2) return rtl.isPasClass(instance);
  467. return true;
  468. }
  469. if (type.isPrototypeOf && type.isPrototypeOf(instance)){
  470. if (mode===1) return rtl.isPasClassInstance(instance);
  471. if (mode===2) return rtl.isPasClass(instance);
  472. return true;
  473. }
  474. if ((typeof type == 'function') && (instance instanceof type)) return true;
  475. return false;
  476. },
  477. Exception: null,
  478. EInvalidCast: null,
  479. EAbstractError: null,
  480. ERangeError: null,
  481. EIntOverflow: null,
  482. EPropWriteOnly: null,
  483. raiseE: function(typename){
  484. var t = rtl[typename];
  485. if (t==null){
  486. var mod = pas.SysUtils;
  487. if (!mod) mod = pas.sysutils;
  488. if (!mod) mod = pas["System.SysUtils"];
  489. if (mod){
  490. t = mod[typename];
  491. if (!t) t = mod[typename.toLowerCase()];
  492. if (!t) t = mod['Exception'];
  493. if (!t) t = mod['exception'];
  494. }
  495. if (t) rtl[typename]=t;
  496. }
  497. if (t) {
  498. if (t.Create){
  499. var e = t.$create("Create");
  500. } else if (t.create) {
  501. var e = t.$create("create");
  502. }
  503. if (e) {
  504. e.FJSError = new Error;
  505. throw e ;
  506. }
  507. }
  508. if (typename === "EInvalidCast") throw new Error("invalid type cast");
  509. if (typename === "EAbstractError") throw new Error("Abstract method called");
  510. if (typename === "ERangeError") throw new Error("range error");
  511. throw typename;
  512. },
  513. as: function(instance,type){
  514. if((instance === null) || rtl.is(instance,type)) return instance;
  515. rtl.raiseE("EInvalidCast");
  516. },
  517. asExt: function(instance,type,mode){
  518. if((instance === null) || rtl.isExt(instance,type,mode)) return instance;
  519. rtl.raiseE("EInvalidCast");
  520. },
  521. createInterface: function(module, name, guid, fnnames, ancestor, initfn, rttiname){
  522. //console.log('createInterface name="'+name+'" guid="'+guid+'" names='+fnnames);
  523. var i = ancestor?Object.create(ancestor):{};
  524. module[name] = i;
  525. i.$module = module;
  526. i.$name = rttiname?rttiname:name;
  527. i.$fullname = module.$name+'.'+i.$name;
  528. i.$guid = guid;
  529. i.$guidr = null;
  530. i.$names = fnnames?fnnames:[];
  531. if (rtl.isFunction(initfn)){
  532. // rtti
  533. if (rtl.debug_rtti) rtl.debug('createInterface '+i.$fullname);
  534. var t = i.$module.$rtti.$Interface(i.$name,{ "interface": i, module: module });
  535. i.$rtti = t;
  536. if (ancestor) t.ancestor = ancestor.$rtti;
  537. if (!t.ancestor) t.ancestor = null;
  538. initfn.call(i);
  539. }
  540. return i;
  541. },
  542. strToGUIDR: function(s,g){
  543. var p = 0;
  544. function n(l){
  545. var h = s.substr(p,l);
  546. p+=l;
  547. return parseInt(h,16);
  548. }
  549. p+=1; // skip {
  550. g.D1 = n(8);
  551. p+=1; // skip -
  552. g.D2 = n(4);
  553. p+=1; // skip -
  554. g.D3 = n(4);
  555. p+=1; // skip -
  556. if (!g.D4) g.D4=[];
  557. g.D4[0] = n(2);
  558. g.D4[1] = n(2);
  559. p+=1; // skip -
  560. for(var i=2; i<8; i++) g.D4[i] = n(2);
  561. return g;
  562. },
  563. guidrToStr: function(g){
  564. if (g.$intf) return g.$intf.$guid;
  565. var h = rtl.hexStr;
  566. var s='{'+h(g.D1,8)+'-'+h(g.D2,4)+'-'+h(g.D3,4)+'-'+h(g.D4[0],2)+h(g.D4[1],2)+'-';
  567. for (var i=2; i<8; i++) s+=h(g.D4[i],2);
  568. s+='}';
  569. return s;
  570. },
  571. createTGUID: function(guid){
  572. var TGuid = (pas.System)?pas.System.TGuid:pas.system.tguid;
  573. var g = rtl.strToGUIDR(guid,TGuid.$new());
  574. return g;
  575. },
  576. getIntfGUIDR: function(intfTypeOrVar){
  577. if (!intfTypeOrVar) return null;
  578. if (!intfTypeOrVar.$guidr){
  579. var g = rtl.createTGUID(intfTypeOrVar.$guid);
  580. if (!intfTypeOrVar.hasOwnProperty('$guid')) intfTypeOrVar = Object.getPrototypeOf(intfTypeOrVar);
  581. g.$intf = intfTypeOrVar;
  582. intfTypeOrVar.$guidr = g;
  583. }
  584. return intfTypeOrVar.$guidr;
  585. },
  586. addIntf: function (aclass, intf, map){
  587. function jmp(fn){
  588. if (typeof(fn)==="function"){
  589. return function(){ return fn.apply(this.$o,arguments); };
  590. } else {
  591. return function(){ rtl.raiseE('EAbstractError'); };
  592. }
  593. }
  594. if(!map) map = {};
  595. var t = intf;
  596. var item = Object.create(t);
  597. if (!aclass.hasOwnProperty('$intfmaps')) aclass.$intfmaps = {};
  598. aclass.$intfmaps[intf.$guid] = item;
  599. do{
  600. var names = t.$names;
  601. if (!names) break;
  602. for (var i=0; i<names.length; i++){
  603. var intfname = names[i];
  604. var fnname = map[intfname];
  605. if (!fnname) fnname = intfname;
  606. //console.log('addIntf: intftype='+t.$name+' index='+i+' intfname="'+intfname+'" fnname="'+fnname+'" old='+typeof(item[intfname]));
  607. item[intfname] = jmp(aclass[fnname]);
  608. }
  609. t = Object.getPrototypeOf(t);
  610. }while(t!=null);
  611. },
  612. getIntfG: function (obj, guid, query){
  613. if (!obj) return null;
  614. //console.log('getIntfG: obj='+obj.$classname+' guid='+guid+' query='+query);
  615. // search
  616. var maps = obj.$intfmaps;
  617. if (!maps) return null;
  618. var item = maps[guid];
  619. if (!item) return null;
  620. // check delegation
  621. //console.log('getIntfG: obj='+obj.$classname+' guid='+guid+' query='+query+' item='+typeof(item));
  622. if (typeof item === 'function') return item.call(obj); // delegate. Note: COM contains _AddRef
  623. // check cache
  624. var intf = null;
  625. if (obj.$interfaces){
  626. intf = obj.$interfaces[guid];
  627. //console.log('getIntfG: obj='+obj.$classname+' guid='+guid+' cache='+typeof(intf));
  628. }
  629. if (!intf){ // intf can be undefined!
  630. intf = Object.create(item);
  631. intf.$o = obj;
  632. if (!obj.$interfaces) obj.$interfaces = {};
  633. obj.$interfaces[guid] = intf;
  634. }
  635. if (typeof(query)==='object'){
  636. // called by queryIntfT
  637. var o = null;
  638. if (intf.QueryInterface(rtl.getIntfGUIDR(query),
  639. {get:function(){ return o; }, set:function(v){ o=v; }}) === 0){
  640. return o;
  641. } else {
  642. return null;
  643. }
  644. } else if(query===2){
  645. // called by TObject.GetInterfaceByStr
  646. if (intf.$kind === 'com') intf._AddRef();
  647. }
  648. return intf;
  649. },
  650. getIntfT: function(obj,intftype){
  651. return rtl.getIntfG(obj,intftype.$guid);
  652. },
  653. queryIntfT: function(obj,intftype){
  654. return rtl.getIntfG(obj,intftype.$guid,intftype);
  655. },
  656. queryIntfIsT: function(obj,intftype){
  657. var i = rtl.getIntfG(obj,intftype.$guid);
  658. if (!i) return false;
  659. if (i.$kind === 'com') i._Release();
  660. return true;
  661. },
  662. asIntfT: function (obj,intftype){
  663. var i = rtl.getIntfG(obj,intftype.$guid);
  664. if (i!==null) return i;
  665. rtl.raiseEInvalidCast();
  666. },
  667. intfIsIntfT: function(intf,intftype){
  668. return (intf!==null) && rtl.queryIntfIsT(intf.$o,intftype);
  669. },
  670. intfAsIntfT: function (intf,intftype){
  671. if (!intf) return null;
  672. var i = rtl.getIntfG(intf.$o,intftype.$guid);
  673. if (i) return i;
  674. rtl.raiseEInvalidCast();
  675. },
  676. intfIsClass: function(intf,classtype){
  677. return (intf!=null) && (rtl.is(intf.$o,classtype));
  678. },
  679. intfAsClass: function(intf,classtype){
  680. if (intf==null) return null;
  681. return rtl.as(intf.$o,classtype);
  682. },
  683. intfToClass: function(intf,classtype){
  684. if ((intf!==null) && rtl.is(intf.$o,classtype)) return intf.$o;
  685. return null;
  686. },
  687. // interface reference counting
  688. intfRefs: { // base object for temporary interface variables
  689. ref: function(id,intf){
  690. // called for temporary interface references needing delayed release
  691. var old = this[id];
  692. //console.log('rtl.intfRefs.ref: id='+id+' old="'+(old?old.$name:'null')+'" intf="'+(intf?intf.$name:'null')+' $o='+(intf?intf.$o:'null'));
  693. if (old){
  694. // called again, e.g. in a loop
  695. delete this[id];
  696. old._Release(); // may fail
  697. }
  698. if(intf) {
  699. this[id]=intf;
  700. }
  701. return intf;
  702. },
  703. free: function(){
  704. //console.log('rtl.intfRefs.free...');
  705. for (var id in this){
  706. if (this.hasOwnProperty(id)){
  707. var intf = this[id];
  708. if (intf){
  709. //console.log('rtl.intfRefs.free: id='+id+' '+intf.$name+' $o='+intf.$o.$classname);
  710. intf._Release();
  711. }
  712. }
  713. }
  714. }
  715. },
  716. createIntfRefs: function(){
  717. //console.log('rtl.createIntfRefs');
  718. return Object.create(rtl.intfRefs);
  719. },
  720. setIntfP: function(path,name,value,skipAddRef){
  721. var old = path[name];
  722. //console.log('rtl.setIntfP path='+path+' name='+name+' old="'+(old?old.$name:'null')+'" value="'+(value?value.$name:'null')+'"');
  723. if (old === value) return;
  724. if (old !== null){
  725. path[name]=null;
  726. old._Release();
  727. }
  728. if (value !== null){
  729. if (!skipAddRef) value._AddRef();
  730. path[name]=value;
  731. }
  732. },
  733. setIntfL: function(old,value,skipAddRef){
  734. //console.log('rtl.setIntfL old="'+(old?old.$name:'null')+'" value="'+(value?value.$name:'null')+'"');
  735. if (old !== value){
  736. if (value!==null){
  737. if (!skipAddRef) value._AddRef();
  738. }
  739. if (old!==null){
  740. old._Release(); // Release after AddRef, to avoid double Release if Release creates an exception
  741. }
  742. } else if (skipAddRef){
  743. if (old!==null){
  744. old._Release(); // value has an AddRef
  745. }
  746. }
  747. return value;
  748. },
  749. _AddRef: function(intf){
  750. //if (intf) console.log('rtl._AddRef intf="'+(intf?intf.$name:'null')+'"');
  751. if (intf) intf._AddRef();
  752. return intf;
  753. },
  754. _Release: function(intf){
  755. //if (intf) console.log('rtl._Release intf="'+(intf?intf.$name:'null')+'"');
  756. if (intf) intf._Release();
  757. return intf;
  758. },
  759. _ReleaseArray: function(a,dim){
  760. if (!a) return null;
  761. for (var i=0; i<a.length; i++){
  762. if (dim<=1){
  763. if (a[i]) a[i]._Release();
  764. } else {
  765. rtl._ReleaseArray(a[i],dim-1);
  766. }
  767. }
  768. return null;
  769. },
  770. trunc: function(a){
  771. return a<0 ? Math.ceil(a) : Math.floor(a);
  772. },
  773. checkMethodCall: function(obj,type){
  774. if (rtl.isObject(obj) && rtl.is(obj,type)) return;
  775. rtl.raiseE("EInvalidCast");
  776. },
  777. oc: function(i){
  778. // overflow check integer
  779. if ((Math.floor(i)===i) && (i>=-0x1fffffffffffff) && (i<=0x1fffffffffffff)) return i;
  780. rtl.raiseE('EIntOverflow');
  781. },
  782. rc: function(i,minval,maxval){
  783. // range check integer
  784. if ((Math.floor(i)===i) && (i>=minval) && (i<=maxval)) return i;
  785. rtl.raiseE('ERangeError');
  786. },
  787. rcc: function(c,minval,maxval){
  788. // range check char
  789. if ((typeof(c)==='string') && (c.length===1)){
  790. var i = c.charCodeAt(0);
  791. if ((i>=minval) && (i<=maxval)) return c;
  792. }
  793. rtl.raiseE('ERangeError');
  794. },
  795. rcSetCharAt: function(s,index,c){
  796. // range check setCharAt
  797. if ((typeof(s)!=='string') || (index<0) || (index>=s.length)) rtl.raiseE('ERangeError');
  798. return rtl.setCharAt(s,index,c);
  799. },
  800. rcCharAt: function(s,index){
  801. // range check charAt
  802. if ((typeof(s)!=='string') || (index<0) || (index>=s.length)) rtl.raiseE('ERangeError');
  803. return s.charAt(index);
  804. },
  805. rcArrR: function(arr,index){
  806. // range check read array
  807. if (Array.isArray(arr) && (typeof(index)==='number') && (index>=0) && (index<arr.length)){
  808. if (arguments.length>2){
  809. // arr,index1,index2,...
  810. arr=arr[index];
  811. for (var i=2; i<arguments.length; i++) arr=rtl.rcArrR(arr,arguments[i]);
  812. return arr;
  813. }
  814. return arr[index];
  815. }
  816. rtl.raiseE('ERangeError');
  817. },
  818. rcArrW: function(arr,index,value){
  819. // range check write array
  820. // arr,index1,index2,...,value
  821. for (var i=3; i<arguments.length; i++){
  822. arr=rtl.rcArrR(arr,index);
  823. index=arguments[i-1];
  824. value=arguments[i];
  825. }
  826. if (Array.isArray(arr) && (typeof(index)==='number') && (index>=0) && (index<arr.length)){
  827. return arr[index]=value;
  828. }
  829. rtl.raiseE('ERangeError');
  830. },
  831. length: function(arr){
  832. return (arr == null) ? 0 : arr.length;
  833. },
  834. arrayRef: function(a){
  835. if (a!=null) rtl.hideProp(a,'$pas2jsrefcnt',1);
  836. return a;
  837. },
  838. arraySetLength: function(arr,defaultvalue,newlength){
  839. var stack = [];
  840. var s = 9999;
  841. for (var i=2; i<arguments.length; i++){
  842. var j = arguments[i];
  843. if (j==='s'){ s = i-2; }
  844. else {
  845. stack.push({ dim:j+0, a:null, i:0, src:null });
  846. }
  847. }
  848. var dimmax = stack.length-1;
  849. var depth = 0;
  850. var lastlen = 0;
  851. var item = null;
  852. var a = null;
  853. var src = arr;
  854. var srclen = 0, oldlen = 0;
  855. do{
  856. if (depth>0){
  857. item=stack[depth-1];
  858. src = (item.src && item.src.length>item.i)?item.src[item.i]:null;
  859. }
  860. if (!src){
  861. a = [];
  862. srclen = 0;
  863. oldlen = 0;
  864. } else if (src.$pas2jsrefcnt>0 || depth>=s){
  865. a = [];
  866. srclen = src.length;
  867. oldlen = srclen;
  868. } else {
  869. a = src;
  870. srclen = 0;
  871. oldlen = a.length;
  872. }
  873. lastlen = stack[depth].dim;
  874. a.length = lastlen;
  875. if (depth>0){
  876. item.a[item.i]=a;
  877. item.i++;
  878. if ((lastlen===0) && (item.i<item.a.length)) continue;
  879. }
  880. if (lastlen>0){
  881. if (depth<dimmax){
  882. item = stack[depth];
  883. item.a = a;
  884. item.i = 0;
  885. item.src = src;
  886. depth++;
  887. continue;
  888. } else {
  889. if (srclen>lastlen) srclen=lastlen;
  890. if (rtl.isArray(defaultvalue)){
  891. // array of dyn array
  892. for (var i=0; i<srclen; i++) a[i]=src[i];
  893. for (var i=oldlen; i<lastlen; i++) a[i]=[];
  894. } else if (rtl.isObject(defaultvalue)) {
  895. if (rtl.isTRecord(defaultvalue)){
  896. // array of record
  897. for (var i=0; i<srclen; i++) a[i]=defaultvalue.$clone(src[i]);
  898. for (var i=oldlen; i<lastlen; i++) a[i]=defaultvalue.$new();
  899. } else {
  900. // array of set
  901. for (var i=0; i<srclen; i++) a[i]=rtl.refSet(src[i]);
  902. for (var i=oldlen; i<lastlen; i++) a[i]={};
  903. }
  904. } else {
  905. for (var i=0; i<srclen; i++) a[i]=src[i];
  906. for (var i=oldlen; i<lastlen; i++) a[i]=defaultvalue;
  907. }
  908. }
  909. }
  910. // backtrack
  911. while ((depth>0) && (stack[depth-1].i>=stack[depth-1].dim)){
  912. depth--;
  913. };
  914. if (depth===0){
  915. if (dimmax===0) return a;
  916. return stack[0].a;
  917. }
  918. }while (true);
  919. },
  920. arrayEq: function(a,b){
  921. if (a===null) return b===null;
  922. if (b===null) return false;
  923. if (a.length!==b.length) return false;
  924. for (var i=0; i<a.length; i++) if (a[i]!==b[i]) return false;
  925. return true;
  926. },
  927. arrayClone: function(type,src,srcpos,endpos,dst,dstpos){
  928. // type: 0 for references, "refset" for calling refSet(), a function for new type()
  929. // src must not be null
  930. // This function does not range check.
  931. if(type === 'refSet') {
  932. for (; srcpos<endpos; srcpos++) dst[dstpos++] = rtl.refSet(src[srcpos]); // ref set
  933. } else if (type === 'slice'){
  934. for (; srcpos<endpos; srcpos++) dst[dstpos++] = src[srcpos].slice(0); // clone static array of simple types
  935. } else if (typeof(type)==='function'){
  936. for (; srcpos<endpos; srcpos++) dst[dstpos++] = type(src[srcpos]); // clone function
  937. } else if (rtl.isTRecord(type)){
  938. for (; srcpos<endpos; srcpos++) dst[dstpos++] = type.$clone(src[srcpos]); // clone record
  939. } else {
  940. for (; srcpos<endpos; srcpos++) dst[dstpos++] = src[srcpos]; // reference
  941. };
  942. },
  943. arrayConcat: function(type){
  944. // type: see rtl.arrayClone
  945. var a = [];
  946. var l = 0;
  947. for (var i=1; i<arguments.length; i++){
  948. var src = arguments[i];
  949. if (src !== null) l+=src.length;
  950. };
  951. a.length = l;
  952. l=0;
  953. for (var i=1; i<arguments.length; i++){
  954. var src = arguments[i];
  955. if (src === null) continue;
  956. rtl.arrayClone(type,src,0,src.length,a,l);
  957. l+=src.length;
  958. };
  959. return a;
  960. },
  961. arrayConcatN: function(){
  962. var a = null;
  963. for (var i=0; i<arguments.length; i++){
  964. var src = arguments[i];
  965. if (src === null) continue;
  966. if (a===null){
  967. a=rtl.arrayRef(src); // Note: concat(a) does not clone
  968. } else if (a['$pas2jsrefcnt']){
  969. a=a.concat(src); // clone a and append src
  970. } else {
  971. for (var i=0; i<src.length; i++){
  972. a.push(src[i]);
  973. }
  974. }
  975. };
  976. return a;
  977. },
  978. arrayPush: function(type,a){
  979. if(a===null){
  980. a=[];
  981. } else if (a['$pas2jsrefcnt']){
  982. a=rtl.arrayCopy(type,a,0,a.length);
  983. }
  984. rtl.arrayClone(type,arguments,2,arguments.length,a,a.length);
  985. return a;
  986. },
  987. arrayPushN: function(a){
  988. if(a===null){
  989. a=[];
  990. } else if (a['$pas2jsrefcnt']){
  991. a=a.concat();
  992. }
  993. for (var i=1; i<arguments.length; i++){
  994. a.push(arguments[i]);
  995. }
  996. return a;
  997. },
  998. arrayCopy: function(type, srcarray, index, count){
  999. // type: see rtl.arrayClone
  1000. // if count is missing, use srcarray.length
  1001. if (srcarray === null) return [];
  1002. if (index < 0) index = 0;
  1003. if (count === undefined) count=srcarray.length;
  1004. var end = index+count;
  1005. if (end>srcarray.length) end = srcarray.length;
  1006. if (index>=end) return [];
  1007. if (type===0){
  1008. return srcarray.slice(index,end);
  1009. } else {
  1010. var a = [];
  1011. a.length = end-index;
  1012. rtl.arrayClone(type,srcarray,index,end,a,0);
  1013. return a;
  1014. }
  1015. },
  1016. arrayInsert: function(item, arr, index){
  1017. if (arr){
  1018. arr.splice(index,0,item);
  1019. return arr;
  1020. } else {
  1021. return [item];
  1022. }
  1023. },
  1024. setCharAt: function(s,index,c){
  1025. return s.substr(0,index)+c+s.substr(index+1);
  1026. },
  1027. getResStr: function(mod,name){
  1028. var rs = mod.$resourcestrings[name];
  1029. return rs.current?rs.current:rs.org;
  1030. },
  1031. createSet: function(){
  1032. var s = {};
  1033. for (var i=0; i<arguments.length; i++){
  1034. if (arguments[i]!=null){
  1035. s[arguments[i]]=true;
  1036. } else {
  1037. var first=arguments[i+=1];
  1038. var last=arguments[i+=1];
  1039. for(var j=first; j<=last; j++) s[j]=true;
  1040. }
  1041. }
  1042. return s;
  1043. },
  1044. cloneSet: function(s){
  1045. var r = {};
  1046. for (var key in s) r[key]=true;
  1047. return r;
  1048. },
  1049. refSet: function(s){
  1050. rtl.hideProp(s,'$shared',true);
  1051. return s;
  1052. },
  1053. includeSet: function(s,enumvalue){
  1054. if (s.$shared) s = rtl.cloneSet(s);
  1055. s[enumvalue] = true;
  1056. return s;
  1057. },
  1058. excludeSet: function(s,enumvalue){
  1059. if (s.$shared) s = rtl.cloneSet(s);
  1060. delete s[enumvalue];
  1061. return s;
  1062. },
  1063. diffSet: function(s,t){
  1064. var r = {};
  1065. for (var key in s) if (!t[key]) r[key]=true;
  1066. return r;
  1067. },
  1068. unionSet: function(s,t){
  1069. var r = {};
  1070. for (var key in s) r[key]=true;
  1071. for (var key in t) r[key]=true;
  1072. return r;
  1073. },
  1074. intersectSet: function(s,t){
  1075. var r = {};
  1076. for (var key in s) if (t[key]) r[key]=true;
  1077. return r;
  1078. },
  1079. symDiffSet: function(s,t){
  1080. var r = {};
  1081. for (var key in s) if (!t[key]) r[key]=true;
  1082. for (var key in t) if (!s[key]) r[key]=true;
  1083. return r;
  1084. },
  1085. eqSet: function(s,t){
  1086. for (var key in s) if (!t[key]) return false;
  1087. for (var key in t) if (!s[key]) return false;
  1088. return true;
  1089. },
  1090. neSet: function(s,t){
  1091. return !rtl.eqSet(s,t);
  1092. },
  1093. leSet: function(s,t){
  1094. for (var key in s) if (!t[key]) return false;
  1095. return true;
  1096. },
  1097. geSet: function(s,t){
  1098. for (var key in t) if (!s[key]) return false;
  1099. return true;
  1100. },
  1101. strSetLength: function(s,newlen){
  1102. var oldlen = s.length;
  1103. if (oldlen > newlen){
  1104. return s.substring(0,newlen);
  1105. } else if (s.repeat){
  1106. // Note: repeat needs ECMAScript6!
  1107. return s+' '.repeat(newlen-oldlen);
  1108. } else {
  1109. while (oldlen<newlen){
  1110. s+=' ';
  1111. oldlen++;
  1112. };
  1113. return s;
  1114. }
  1115. },
  1116. spaceLeft: function(s,width){
  1117. var l=s.length;
  1118. if (l>=width) return s;
  1119. if (s.repeat){
  1120. // Note: repeat needs ECMAScript6!
  1121. return ' '.repeat(width-l) + s;
  1122. } else {
  1123. while (l<width){
  1124. s=' '+s;
  1125. l++;
  1126. };
  1127. return s;
  1128. };
  1129. },
  1130. floatToStr: function(d,w,p){
  1131. // input 1-3 arguments: double, width, precision
  1132. if (arguments.length>2){
  1133. return rtl.spaceLeft(d.toFixed(p),w);
  1134. } else {
  1135. // exponent width
  1136. var pad = "";
  1137. var ad = Math.abs(d);
  1138. if (((ad>1) && (ad<1.0e+10)) || ((ad>1.e-10) && (ad<1))) {
  1139. pad='00';
  1140. } else if ((ad>1) && (ad<1.0e+100) || (ad<1.e-10)) {
  1141. pad='0';
  1142. }
  1143. if (arguments.length<2) {
  1144. w=24;
  1145. } else if (w<9) {
  1146. w=9;
  1147. }
  1148. var p = w-8;
  1149. var s=(d>0 ? " " : "" ) + d.toExponential(p);
  1150. s=s.replace(/e(.)/,'E$1'+pad);
  1151. return rtl.spaceLeft(s,w);
  1152. }
  1153. },
  1154. valEnum: function(s, enumType, setCodeFn){
  1155. s = s.toLowerCase();
  1156. for (var key in enumType){
  1157. if((typeof(key)==='string') && (key.toLowerCase()===s)){
  1158. setCodeFn(0);
  1159. return enumType[key];
  1160. }
  1161. }
  1162. setCodeFn(1);
  1163. return 0;
  1164. },
  1165. lw: function(l){
  1166. // fix longword bitwise operation
  1167. return l<0?l+0x100000000:l;
  1168. },
  1169. and: function(a,b){
  1170. var hi = 0x80000000;
  1171. var low = 0x7fffffff;
  1172. var h = (a / hi) & (b / hi);
  1173. var l = (a & low) & (b & low);
  1174. return h*hi + l;
  1175. },
  1176. or: function(a,b){
  1177. var hi = 0x80000000;
  1178. var low = 0x7fffffff;
  1179. var h = (a / hi) | (b / hi);
  1180. var l = (a & low) | (b & low);
  1181. return h*hi + l;
  1182. },
  1183. xor: function(a,b){
  1184. var hi = 0x80000000;
  1185. var low = 0x7fffffff;
  1186. var h = (a / hi) ^ (b / hi);
  1187. var l = (a & low) ^ (b & low);
  1188. return h*hi + l;
  1189. },
  1190. shr: function(a,b){
  1191. if (a<0) a += rtl.hiInt;
  1192. if (a<0x80000000) return a >> b;
  1193. if (b<=0) return a;
  1194. if (b>54) return 0;
  1195. return Math.floor(a / Math.pow(2,b));
  1196. },
  1197. shl: function(a,b){
  1198. if (a<0) a += rtl.hiInt;
  1199. if (b<=0) return a;
  1200. if (b>54) return 0;
  1201. var r = a * Math.pow(2,b);
  1202. if (r <= rtl.hiInt) return r;
  1203. return r % rtl.hiInt;
  1204. },
  1205. initRTTI: function(){
  1206. if (rtl.debug_rtti) rtl.debug('initRTTI');
  1207. // base types
  1208. rtl.tTypeInfo = { name: "tTypeInfo", kind: 0, $module: null, attr: null };
  1209. function newBaseTI(name,kind,ancestor){
  1210. if (!ancestor) ancestor = rtl.tTypeInfo;
  1211. if (rtl.debug_rtti) rtl.debug('initRTTI.newBaseTI "'+name+'" '+kind+' ("'+ancestor.name+'")');
  1212. var t = Object.create(ancestor);
  1213. t.name = name;
  1214. t.kind = kind;
  1215. rtl[name] = t;
  1216. return t;
  1217. };
  1218. function newBaseInt(name,minvalue,maxvalue,ordtype){
  1219. var t = newBaseTI(name,1 /* tkInteger */,rtl.tTypeInfoInteger);
  1220. t.minvalue = minvalue;
  1221. t.maxvalue = maxvalue;
  1222. t.ordtype = ordtype;
  1223. return t;
  1224. };
  1225. newBaseTI("tTypeInfoInteger",1 /* tkInteger */);
  1226. newBaseInt("shortint",-0x80,0x7f,0);
  1227. newBaseInt("byte",0,0xff,1);
  1228. newBaseInt("smallint",-0x8000,0x7fff,2);
  1229. newBaseInt("word",0,0xffff,3);
  1230. newBaseInt("longint",-0x80000000,0x7fffffff,4);
  1231. newBaseInt("longword",0,0xffffffff,5);
  1232. newBaseInt("nativeint",-0x10000000000000,0xfffffffffffff,6);
  1233. newBaseInt("nativeuint",0,0xfffffffffffff,7);
  1234. newBaseInt("char",0,65535,3 /* word */).kind=2 /* tkChar */;
  1235. newBaseTI("string",3 /* tkString */);
  1236. newBaseTI("tTypeInfoEnum",4 /* tkEnumeration */,rtl.tTypeInfoInteger);
  1237. newBaseTI("tTypeInfoSet",5 /* tkSet */);
  1238. newBaseTI("double",6 /* tkDouble */);
  1239. newBaseTI("boolean",7 /* tkBool */);
  1240. newBaseTI("tTypeInfoProcVar",8 /* tkProcVar */);
  1241. newBaseTI("tTypeInfoMethodVar",9 /* tkMethod */,rtl.tTypeInfoProcVar);
  1242. newBaseTI("tTypeInfoArray",10 /* tkArray */);
  1243. newBaseTI("tTypeInfoDynArray",11 /* tkDynArray */);
  1244. newBaseTI("tTypeInfoPointer",15 /* tkPointer */);
  1245. var t = newBaseTI("pointer",15 /* tkPointer */,rtl.tTypeInfoPointer);
  1246. t.reftype = null;
  1247. newBaseTI("jsvalue",16 /* tkJSValue */);
  1248. newBaseTI("tTypeInfoRefToProcVar",17 /* tkRefToProcVar */,rtl.tTypeInfoProcVar);
  1249. // member kinds
  1250. rtl.tTypeMember = { attr: null };
  1251. function newMember(name,kind){
  1252. var m = Object.create(rtl.tTypeMember);
  1253. m.name = name;
  1254. m.kind = kind;
  1255. rtl[name] = m;
  1256. };
  1257. newMember("tTypeMemberField",1); // tmkField
  1258. newMember("tTypeMemberMethod",2); // tmkMethod
  1259. newMember("tTypeMemberProperty",3); // tmkProperty
  1260. // base object for storing members: a simple object
  1261. rtl.tTypeMembers = {};
  1262. // tTypeInfoStruct - base object for tTypeInfoClass, tTypeInfoRecord, tTypeInfoInterface
  1263. var tis = newBaseTI("tTypeInfoStruct",0);
  1264. tis.$addMember = function(name,ancestor,vis,options){
  1265. if (rtl.debug_rtti){
  1266. if (!rtl.hasString(name) || (name.charAt()==='$')) throw 'invalid member "'+name+'", this="'+this.name+'"';
  1267. if (!rtl.is(ancestor,rtl.tTypeMember)) throw 'invalid ancestor "'+ancestor+':'+ancestor.name+'", "'+this.name+'.'+name+'"';
  1268. if ((options!=undefined) && (typeof(options)!='object')) throw 'invalid options "'+options+'", "'+this.name+'.'+name+'"';
  1269. };
  1270. var t = Object.create(ancestor);
  1271. t.name = name;
  1272. this.members[name] = t;
  1273. this.names.push(name);
  1274. t.visibility = vis;
  1275. if (rtl.isObject(options)){
  1276. for (var key in options) if (options.hasOwnProperty(key)) t[key] = options[key];
  1277. };
  1278. return t;
  1279. };
  1280. tis.addField = function(name,type,vis,options){
  1281. var t = this.$addMember(name,rtl.tTypeMemberField,vis?vis:2,options);
  1282. if (rtl.debug_rtti){
  1283. if (!rtl.is(type,rtl.tTypeInfo)) throw 'invalid type "'+type+'", "'+this.name+'.'+name+'"';
  1284. };
  1285. t.typeinfo = type;
  1286. this.fields.push(name);
  1287. return t;
  1288. };
  1289. tis.addFields = function(){
  1290. var i=0;
  1291. while(i<arguments.length){
  1292. var name = arguments[i++];
  1293. var type = arguments[i++];
  1294. if ((i<arguments.length) && (typeof(arguments[i])==='object')){
  1295. this.addField(name,type,arguments[i++]);
  1296. } else {
  1297. this.addField(name,type);
  1298. };
  1299. };
  1300. };
  1301. tis.addMethod = function(name,methodkind,params,vis,result,flags,options){
  1302. var t = this.$addMember(name,rtl.tTypeMemberMethod,vis?vis:2,options);
  1303. t.methodkind = methodkind;
  1304. t.procsig = rtl.newTIProcSig(params,result,flags);
  1305. this.methods.push(name);
  1306. return t;
  1307. };
  1308. tis.addProperty = function(name,flags,result,getter,setter,vis,options){
  1309. var t = this.$addMember(name,rtl.tTypeMemberProperty,vis?vis:4,options);
  1310. t.flags = flags;
  1311. t.typeinfo = result;
  1312. t.getter = getter;
  1313. t.setter = setter;
  1314. // Note: in options: params, stored, defaultvalue
  1315. t.params = rtl.isArray(t.params) ? rtl.newTIParams(t.params) : null;
  1316. this.properties.push(name);
  1317. if (!rtl.isString(t.stored)) t.stored = "";
  1318. return t;
  1319. };
  1320. tis.getField = function(index){
  1321. return this.members[this.fields[index]];
  1322. };
  1323. tis.getMethod = function(index){
  1324. return this.members[this.methods[index]];
  1325. };
  1326. tis.getProperty = function(index){
  1327. return this.members[this.properties[index]];
  1328. };
  1329. newBaseTI("tTypeInfoRecord",12 /* tkRecord */,rtl.tTypeInfoStruct);
  1330. newBaseTI("tTypeInfoClass",13 /* tkClass */,rtl.tTypeInfoStruct);
  1331. newBaseTI("tTypeInfoClassRef",14 /* tkClassRef */);
  1332. newBaseTI("tTypeInfoInterface",18 /* tkInterface */,rtl.tTypeInfoStruct);
  1333. newBaseTI("tTypeInfoHelper",19 /* tkHelper */,rtl.tTypeInfoStruct);
  1334. newBaseTI("tTypeInfoExtClass",20 /* tkExtClass */,rtl.tTypeInfoClass);
  1335. },
  1336. tSectionRTTI: {
  1337. $module: null,
  1338. $inherited: function(name,ancestor,o){
  1339. if (rtl.debug_rtti){
  1340. rtl.debug('tSectionRTTI.newTI "'+(this.$module?this.$module.$name:"(no module)")
  1341. +'"."'+name+'" ('+ancestor.name+') '+(o?'init':'forward'));
  1342. };
  1343. var t = this[name];
  1344. if (t){
  1345. if (!t.$forward) throw 'duplicate type "'+name+'"';
  1346. if (!ancestor.isPrototypeOf(t)) throw 'typeinfo ancestor mismatch "'+name+'" ancestor="'+ancestor.name+'" t.name="'+t.name+'"';
  1347. } else {
  1348. t = Object.create(ancestor);
  1349. t.name = name;
  1350. t.$module = this.$module;
  1351. this[name] = t;
  1352. }
  1353. if (o){
  1354. delete t.$forward;
  1355. for (var key in o) if (o.hasOwnProperty(key)) t[key]=o[key];
  1356. } else {
  1357. t.$forward = true;
  1358. }
  1359. return t;
  1360. },
  1361. $Scope: function(name,ancestor,o){
  1362. var t=this.$inherited(name,ancestor,o);
  1363. t.members = {};
  1364. t.names = [];
  1365. t.fields = [];
  1366. t.methods = [];
  1367. t.properties = [];
  1368. return t;
  1369. },
  1370. $TI: function(name,kind,o){ var t=this.$inherited(name,rtl.tTypeInfo,o); t.kind = kind; return t; },
  1371. $Int: function(name,o){ return this.$inherited(name,rtl.tTypeInfoInteger,o); },
  1372. $Enum: function(name,o){ return this.$inherited(name,rtl.tTypeInfoEnum,o); },
  1373. $Set: function(name,o){ return this.$inherited(name,rtl.tTypeInfoSet,o); },
  1374. $StaticArray: function(name,o){ return this.$inherited(name,rtl.tTypeInfoArray,o); },
  1375. $DynArray: function(name,o){ return this.$inherited(name,rtl.tTypeInfoDynArray,o); },
  1376. $ProcVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoProcVar,o); },
  1377. $RefToProcVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoRefToProcVar,o); },
  1378. $MethodVar: function(name,o){ return this.$inherited(name,rtl.tTypeInfoMethodVar,o); },
  1379. $Record: function(name,o){ return this.$Scope(name,rtl.tTypeInfoRecord,o); },
  1380. $Class: function(name,o){ return this.$Scope(name,rtl.tTypeInfoClass,o); },
  1381. $ClassRef: function(name,o){ return this.$inherited(name,rtl.tTypeInfoClassRef,o); },
  1382. $Pointer: function(name,o){ return this.$inherited(name,rtl.tTypeInfoPointer,o); },
  1383. $Interface: function(name,o){ return this.$Scope(name,rtl.tTypeInfoInterface,o); },
  1384. $Helper: function(name,o){ return this.$Scope(name,rtl.tTypeInfoHelper,o); },
  1385. $ExtClass: function(name,o){ return this.$Scope(name,rtl.tTypeInfoExtClass,o); }
  1386. },
  1387. newTIParam: function(param){
  1388. // param is an array, 0=name, 1=type, 2=optional flags
  1389. var t = {
  1390. name: param[0],
  1391. typeinfo: param[1],
  1392. flags: (rtl.isNumber(param[2]) ? param[2] : 0)
  1393. };
  1394. return t;
  1395. },
  1396. newTIParams: function(list){
  1397. // list: optional array of [paramname,typeinfo,optional flags]
  1398. var params = [];
  1399. if (rtl.isArray(list)){
  1400. for (var i=0; i<list.length; i++) params.push(rtl.newTIParam(list[i]));
  1401. };
  1402. return params;
  1403. },
  1404. newTIProcSig: function(params,result,flags){
  1405. var s = {
  1406. params: rtl.newTIParams(params),
  1407. resulttype: result?result:null,
  1408. flags: flags?flags:0
  1409. };
  1410. return s;
  1411. },
  1412. addResource: function(aRes){
  1413. rtl.$res[aRes.name]=aRes;
  1414. },
  1415. getResource: function(aName){
  1416. var res = rtl.$res[aName];
  1417. if (res !== undefined) {
  1418. return res;
  1419. } else {
  1420. return null;
  1421. }
  1422. },
  1423. getResourceList: function(){
  1424. return Object.keys(rtl.$res);
  1425. }
  1426. }
  1427. rtl.module("System",[],function () {
  1428. "use strict";
  1429. var $mod = this;
  1430. var $impl = $mod.$impl;
  1431. this.sLineBreak = "\n";
  1432. this.TTextLineBreakStyle = {"0": "tlbsLF", tlbsLF: 0, "1": "tlbsCRLF", tlbsCRLF: 1, "2": "tlbsCR", tlbsCR: 2};
  1433. rtl.createClass(this,"TObject",null,function () {
  1434. this.$init = function () {
  1435. };
  1436. this.$final = function () {
  1437. };
  1438. this.Create = function () {
  1439. return this;
  1440. };
  1441. this.Destroy = function () {
  1442. };
  1443. this.Free = function () {
  1444. this.$destroy("Destroy");
  1445. };
  1446. this.FieldAddress = function (aName) {
  1447. var Result = null;
  1448. Result = null;
  1449. if (aName === "") return Result;
  1450. var aClass = this.$class;
  1451. var ClassTI = null;
  1452. var myName = aName.toLowerCase();
  1453. var MemberTI = null;
  1454. while (aClass !== null) {
  1455. ClassTI = aClass.$rtti;
  1456. for (var i = 0, $end2 = ClassTI.fields.length - 1; i <= $end2; i++) {
  1457. MemberTI = ClassTI.getField(i);
  1458. if (MemberTI.name.toLowerCase() === myName) {
  1459. return MemberTI;
  1460. };
  1461. };
  1462. aClass = aClass.$ancestor ? aClass.$ancestor : null;
  1463. };
  1464. return Result;
  1465. };
  1466. this.AfterConstruction = function () {
  1467. };
  1468. this.BeforeDestruction = function () {
  1469. };
  1470. });
  1471. this.vtInteger = 0;
  1472. this.vtExtended = 3;
  1473. this.vtWideChar = 9;
  1474. this.vtCurrency = 12;
  1475. this.vtUnicodeString = 18;
  1476. this.vtNativeInt = 19;
  1477. rtl.recNewT(this,"TVarRec",function () {
  1478. this.VType = 0;
  1479. this.VJSValue = undefined;
  1480. this.$eq = function (b) {
  1481. return (this.VType === b.VType) && (this.VJSValue === b.VJSValue) && (this.VJSValue === b.VJSValue) && (this.VJSValue === b.VJSValue) && (this.VJSValue === b.VJSValue) && (this.VJSValue === b.VJSValue) && (this.VJSValue === b.VJSValue) && (this.VJSValue === b.VJSValue);
  1482. };
  1483. this.$assign = function (s) {
  1484. this.VType = s.VType;
  1485. this.VJSValue = s.VJSValue;
  1486. this.VJSValue = s.VJSValue;
  1487. this.VJSValue = s.VJSValue;
  1488. this.VJSValue = s.VJSValue;
  1489. this.VJSValue = s.VJSValue;
  1490. this.VJSValue = s.VJSValue;
  1491. this.VJSValue = s.VJSValue;
  1492. return this;
  1493. };
  1494. });
  1495. this.VarRecs = function () {
  1496. var Result = [];
  1497. var i = 0;
  1498. var v = null;
  1499. Result = [];
  1500. while (i < arguments.length) {
  1501. v = $mod.TVarRec.$new();
  1502. v.VType = rtl.trunc(arguments[i]);
  1503. i += 1;
  1504. v.VJSValue = arguments[i];
  1505. i += 1;
  1506. Result.push($mod.TVarRec.$clone(v));
  1507. };
  1508. return Result;
  1509. };
  1510. this.Trunc = function (A) {
  1511. if (!Math.trunc) {
  1512. Math.trunc = function(v) {
  1513. v = +v;
  1514. if (!isFinite(v)) return v;
  1515. return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
  1516. };
  1517. }
  1518. $mod.Trunc = Math.trunc;
  1519. return Math.trunc(A);
  1520. };
  1521. this.DefaultTextLineBreakStyle = 0;
  1522. this.Int = function (A) {
  1523. var Result = 0.0;
  1524. Result = $mod.Trunc(A);
  1525. return Result;
  1526. };
  1527. this.Copy = function (S, Index, Size) {
  1528. if (Index<1) Index = 1;
  1529. return (Size>0) ? S.substring(Index-1,Index+Size-1) : "";
  1530. };
  1531. this.Copy$1 = function (S, Index) {
  1532. if (Index<1) Index = 1;
  1533. return S.substr(Index-1);
  1534. };
  1535. this.Delete = function (S, Index, Size) {
  1536. var h = "";
  1537. if ((Index < 1) || (Index > S.get().length) || (Size <= 0)) return;
  1538. h = S.get();
  1539. S.set($mod.Copy(h,1,Index - 1) + $mod.Copy$1(h,Index + Size));
  1540. };
  1541. this.Pos = function (Search, InString) {
  1542. return InString.indexOf(Search)+1;
  1543. };
  1544. this.Insert = function (Insertion, Target, Index) {
  1545. var t = "";
  1546. if (Insertion === "") return;
  1547. t = Target.get();
  1548. if (Index < 1) {
  1549. Target.set(Insertion + t)}
  1550. else if (Index > t.length) {
  1551. Target.set(t + Insertion)}
  1552. else Target.set($mod.Copy(t,1,Index - 1) + Insertion + $mod.Copy(t,Index,t.length));
  1553. };
  1554. this.upcase = function (c) {
  1555. return c.toUpperCase();
  1556. };
  1557. this.val = function (S, NI, Code) {
  1558. NI.set($impl.valint(S,-9007199254740991,9007199254740991,Code));
  1559. };
  1560. this.StringOfChar = function (c, l) {
  1561. var Result = "";
  1562. var i = 0;
  1563. if ((l>0) && c.repeat) return c.repeat(l);
  1564. Result = "";
  1565. for (var $l = 1, $end = l; $l <= $end; $l++) {
  1566. i = $l;
  1567. Result = Result + c;
  1568. };
  1569. return Result;
  1570. };
  1571. this.Writeln = function () {
  1572. var i = 0;
  1573. var l = 0;
  1574. var s = "";
  1575. l = arguments.length - 1;
  1576. if ($impl.WriteCallBack != null) {
  1577. for (var $l = 0, $end = l; $l <= $end; $l++) {
  1578. i = $l;
  1579. $impl.WriteCallBack(arguments[i],i === l);
  1580. };
  1581. } else {
  1582. s = $impl.WriteBuf;
  1583. for (var $l1 = 0, $end1 = l; $l1 <= $end1; $l1++) {
  1584. i = $l1;
  1585. s = s + ("" + arguments[i]);
  1586. };
  1587. console.log(s);
  1588. $impl.WriteBuf = "";
  1589. };
  1590. };
  1591. this.Assigned = function (V) {
  1592. return (V!=undefined) && (V!=null) && (!rtl.isArray(V) || (V.length > 0));
  1593. };
  1594. $mod.$implcode = function () {
  1595. $impl.WriteBuf = "";
  1596. $impl.WriteCallBack = null;
  1597. $impl.valint = function (S, MinVal, MaxVal, Code) {
  1598. var Result = 0;
  1599. var x = 0.0;
  1600. if (S === "") {
  1601. Code.set(1);
  1602. return Result;
  1603. };
  1604. x = Number(S);
  1605. if (isNaN(x)) {
  1606. var $tmp = $mod.Copy(S,1,1);
  1607. if ($tmp === "$") {
  1608. x = Number("0x" + $mod.Copy$1(S,2))}
  1609. else if ($tmp === "&") {
  1610. x = Number("0o" + $mod.Copy$1(S,2))}
  1611. else if ($tmp === "%") {
  1612. x = Number("0b" + $mod.Copy$1(S,2))}
  1613. else {
  1614. Code.set(1);
  1615. return Result;
  1616. };
  1617. };
  1618. if (isNaN(x) || (x !== $mod.Int(x))) {
  1619. Code.set(1)}
  1620. else if ((x < MinVal) || (x > MaxVal)) {
  1621. Code.set(2)}
  1622. else {
  1623. Result = $mod.Trunc(x);
  1624. Code.set(0);
  1625. };
  1626. return Result;
  1627. };
  1628. };
  1629. $mod.$init = function () {
  1630. rtl.exitcode = 0;
  1631. };
  1632. },[]);
  1633. rtl.module("RTLConsts",["System"],function () {
  1634. "use strict";
  1635. var $mod = this;
  1636. $mod.$resourcestrings = {SArgumentMissing: {org: 'Missing argument in format "%s"'}, SInvalidFormat: {org: 'Invalid format specifier : "%s"'}, SInvalidArgIndex: {org: 'Invalid argument index in format: "%s"'}, SListCapacityError: {org: "List capacity (%s) exceeded."}, SListCountError: {org: "List count (%s) out of bounds."}, SListIndexError: {org: "List index (%s) out of bounds"}, SSortedListError: {org: "Operation not allowed on sorted list"}, SDuplicateString: {org: "String list does not allow duplicates"}, SErrFindNeedsSortedList: {org: "Cannot use find on unsorted list"}, SInvalidName: {org: 'Invalid component name: "%s"'}, SDuplicateName: {org: 'Duplicate component name: "%s"'}, SErrInvalidInteger: {org: 'Invalid integer value: "%s"'}};
  1637. });
  1638. rtl.module("Types",["System"],function () {
  1639. "use strict";
  1640. var $mod = this;
  1641. this.TDuplicates = {"0": "dupIgnore", dupIgnore: 0, "1": "dupAccept", dupAccept: 1, "2": "dupError", dupError: 2};
  1642. },[]);
  1643. rtl.module("JS",["System","Types"],function () {
  1644. "use strict";
  1645. var $mod = this;
  1646. rtl.createClass(this,"EJS",pas.System.TObject,function () {
  1647. this.$init = function () {
  1648. pas.System.TObject.$init.call(this);
  1649. this.FMessage = "";
  1650. };
  1651. this.Create$1 = function (Msg) {
  1652. this.FMessage = Msg;
  1653. return this;
  1654. };
  1655. });
  1656. this.AsIntNumber = function (v) {
  1657. return Number(v);
  1658. };
  1659. this.New = function (aElements) {
  1660. var Result = null;
  1661. var L = 0;
  1662. var I = 0;
  1663. var S = "";
  1664. L = rtl.length(aElements);
  1665. if ((L % 2) === 1) throw $mod.EJS.$create("Create$1",["Number of arguments must be even"]);
  1666. I = 0;
  1667. while (I < L) {
  1668. if (!rtl.isString(aElements[I])) {
  1669. S = String(I);
  1670. throw $mod.EJS.$create("Create$1",["Argument " + S + " must be a string."]);
  1671. };
  1672. I += 2;
  1673. };
  1674. I = 0;
  1675. Result = new Object();
  1676. while (I < L) {
  1677. S = "" + aElements[I];
  1678. Result[S] = aElements[I + 1];
  1679. I += 2;
  1680. };
  1681. return Result;
  1682. };
  1683. this.isDefined = function (v) {
  1684. return !(v == undefined);
  1685. };
  1686. this.JSClassName = function (aObj) {
  1687. var Result = "";
  1688. Result = "";
  1689. if (aObj === null) return Result;
  1690. return aObj.constructor.name;
  1691. return Result;
  1692. };
  1693. this.HaveSharedArrayBuffer = function () {
  1694. return (typeof SharedArrayBuffer !== 'undefined');
  1695. };
  1696. this.SharedToNonShared = function (aBuffer) {
  1697. var Result = null;
  1698. var Src = null;
  1699. var Dest = null;
  1700. if ($mod.HaveSharedArrayBuffer() && rtl.isExt(aBuffer,SharedArrayBuffer)) {
  1701. Result = new ArrayBuffer(aBuffer.byteLength);
  1702. Src = new Uint8Array(aBuffer);
  1703. Dest = new Uint8Array(Result);
  1704. Dest.set(Src);
  1705. } else Result = aBuffer;
  1706. return Result;
  1707. };
  1708. this.SharedToNonShared$1 = function (aArray, aWordSized) {
  1709. var Result = null;
  1710. var Buf = null;
  1711. if ($mod.HaveSharedArrayBuffer() && rtl.isExt(aArray.buffer,SharedArrayBuffer)) {
  1712. Buf = aArray.buffer.slice(aArray.byteOffset,aArray.byteOffset + aArray.byteLength);
  1713. if (aWordSized) {
  1714. Result = new Uint16Array($mod.SharedToNonShared(Buf))}
  1715. else Result = new Uint8Array($mod.SharedToNonShared(Buf));
  1716. } else Result = aArray;
  1717. return Result;
  1718. };
  1719. });
  1720. rtl.module("SysUtils",["System","RTLConsts","JS"],function () {
  1721. "use strict";
  1722. var $mod = this;
  1723. var $impl = $mod.$impl;
  1724. this.FreeAndNil = function (Obj) {
  1725. var o = null;
  1726. o = Obj.get();
  1727. if (o === null) return;
  1728. Obj.set(null);
  1729. o.$destroy("Destroy");
  1730. };
  1731. rtl.recNewT(this,"TFormatSettings",function () {
  1732. this.CurrencyDecimals = 0;
  1733. this.CurrencyFormat = 0;
  1734. this.CurrencyString = "";
  1735. this.DateSeparator = "";
  1736. this.DecimalSeparator = "";
  1737. this.LongDateFormat = "";
  1738. this.LongTimeFormat = "";
  1739. this.NegCurrFormat = 0;
  1740. this.ShortDateFormat = "";
  1741. this.ShortTimeFormat = "";
  1742. this.ThousandSeparator = "";
  1743. this.TimeAMString = "";
  1744. this.TimePMString = "";
  1745. this.TimeSeparator = "";
  1746. this.TwoDigitYearCenturyWindow = 0;
  1747. this.InitLocaleHandler = null;
  1748. this.$new = function () {
  1749. var r = Object.create(this);
  1750. r.DateTimeToStrFormat = rtl.arraySetLength(null,"",2);
  1751. r.LongDayNames = rtl.arraySetLength(null,"",7);
  1752. r.LongMonthNames = rtl.arraySetLength(null,"",12);
  1753. r.ShortDayNames = rtl.arraySetLength(null,"",7);
  1754. r.ShortMonthNames = rtl.arraySetLength(null,"",12);
  1755. return r;
  1756. };
  1757. this.$eq = function (b) {
  1758. return (this.CurrencyDecimals === b.CurrencyDecimals) && (this.CurrencyFormat === b.CurrencyFormat) && (this.CurrencyString === b.CurrencyString) && (this.DateSeparator === b.DateSeparator) && rtl.arrayEq(this.DateTimeToStrFormat,b.DateTimeToStrFormat) && (this.DecimalSeparator === b.DecimalSeparator) && (this.LongDateFormat === b.LongDateFormat) && rtl.arrayEq(this.LongDayNames,b.LongDayNames) && rtl.arrayEq(this.LongMonthNames,b.LongMonthNames) && (this.LongTimeFormat === b.LongTimeFormat) && (this.NegCurrFormat === b.NegCurrFormat) && (this.ShortDateFormat === b.ShortDateFormat) && rtl.arrayEq(this.ShortDayNames,b.ShortDayNames) && rtl.arrayEq(this.ShortMonthNames,b.ShortMonthNames) && (this.ShortTimeFormat === b.ShortTimeFormat) && (this.ThousandSeparator === b.ThousandSeparator) && (this.TimeAMString === b.TimeAMString) && (this.TimePMString === b.TimePMString) && (this.TimeSeparator === b.TimeSeparator) && (this.TwoDigitYearCenturyWindow === b.TwoDigitYearCenturyWindow);
  1759. };
  1760. this.$assign = function (s) {
  1761. this.CurrencyDecimals = s.CurrencyDecimals;
  1762. this.CurrencyFormat = s.CurrencyFormat;
  1763. this.CurrencyString = s.CurrencyString;
  1764. this.DateSeparator = s.DateSeparator;
  1765. this.DateTimeToStrFormat = s.DateTimeToStrFormat.slice(0);
  1766. this.DecimalSeparator = s.DecimalSeparator;
  1767. this.LongDateFormat = s.LongDateFormat;
  1768. this.LongDayNames = s.LongDayNames.slice(0);
  1769. this.LongMonthNames = s.LongMonthNames.slice(0);
  1770. this.LongTimeFormat = s.LongTimeFormat;
  1771. this.NegCurrFormat = s.NegCurrFormat;
  1772. this.ShortDateFormat = s.ShortDateFormat;
  1773. this.ShortDayNames = s.ShortDayNames.slice(0);
  1774. this.ShortMonthNames = s.ShortMonthNames.slice(0);
  1775. this.ShortTimeFormat = s.ShortTimeFormat;
  1776. this.ThousandSeparator = s.ThousandSeparator;
  1777. this.TimeAMString = s.TimeAMString;
  1778. this.TimePMString = s.TimePMString;
  1779. this.TimeSeparator = s.TimeSeparator;
  1780. this.TwoDigitYearCenturyWindow = s.TwoDigitYearCenturyWindow;
  1781. return this;
  1782. };
  1783. this.GetJSLocale = function () {
  1784. return Intl.DateTimeFormat().resolvedOptions().locale;
  1785. };
  1786. this.Create = function () {
  1787. var Result = $mod.TFormatSettings.$new();
  1788. Result.$assign($mod.TFormatSettings.Create$1($mod.TFormatSettings.GetJSLocale()));
  1789. return Result;
  1790. };
  1791. this.Create$1 = function (ALocale) {
  1792. var Result = $mod.TFormatSettings.$new();
  1793. Result.LongDayNames = $impl.DefaultLongDayNames.slice(0);
  1794. Result.ShortDayNames = $impl.DefaultShortDayNames.slice(0);
  1795. Result.ShortMonthNames = $impl.DefaultShortMonthNames.slice(0);
  1796. Result.LongMonthNames = $impl.DefaultLongMonthNames.slice(0);
  1797. Result.DateTimeToStrFormat[0] = "c";
  1798. Result.DateTimeToStrFormat[1] = "f";
  1799. Result.DateSeparator = "-";
  1800. Result.TimeSeparator = ":";
  1801. Result.ShortDateFormat = "yyyy-mm-dd";
  1802. Result.LongDateFormat = "ddd, yyyy-mm-dd";
  1803. Result.ShortTimeFormat = "hh:nn";
  1804. Result.LongTimeFormat = "hh:nn:ss";
  1805. Result.DecimalSeparator = ".";
  1806. Result.ThousandSeparator = ",";
  1807. Result.TimeAMString = "AM";
  1808. Result.TimePMString = "PM";
  1809. Result.TwoDigitYearCenturyWindow = 50;
  1810. Result.CurrencyFormat = 0;
  1811. Result.NegCurrFormat = 0;
  1812. Result.CurrencyDecimals = 2;
  1813. Result.CurrencyString = "$";
  1814. if ($mod.TFormatSettings.InitLocaleHandler != null) $mod.TFormatSettings.InitLocaleHandler($mod.UpperCase(ALocale),$mod.TFormatSettings.$clone(Result));
  1815. return Result;
  1816. };
  1817. },true);
  1818. rtl.createClass(this,"Exception",pas.System.TObject,function () {
  1819. this.LogMessageOnCreate = false;
  1820. this.$init = function () {
  1821. pas.System.TObject.$init.call(this);
  1822. this.fMessage = "";
  1823. this.FJSError = null;
  1824. };
  1825. this.$final = function () {
  1826. this.FJSError = undefined;
  1827. pas.System.TObject.$final.call(this);
  1828. };
  1829. this.Create$1 = function (Msg) {
  1830. this.fMessage = Msg;
  1831. this.FJSError = new Error();
  1832. if (this.LogMessageOnCreate) pas.System.Writeln("Created exception ",this.$classname," with message: ",Msg);
  1833. return this;
  1834. };
  1835. this.CreateFmt = function (Msg, Args) {
  1836. this.Create$1($mod.Format(Msg,Args));
  1837. return this;
  1838. };
  1839. });
  1840. rtl.createClass(this,"EExternal",this.Exception,function () {
  1841. });
  1842. rtl.createClass(this,"EInvalidCast",this.Exception,function () {
  1843. });
  1844. rtl.createClass(this,"EConvertError",this.Exception,function () {
  1845. });
  1846. rtl.createClass(this,"EIntError",this.EExternal,function () {
  1847. });
  1848. rtl.createClass(this,"ERangeError",this.EIntError,function () {
  1849. });
  1850. rtl.createClass(this,"EExternalException",this.EExternal,function () {
  1851. });
  1852. rtl.createClass(this,"EAbstractError",this.Exception,function () {
  1853. });
  1854. this.TrimLeft = function (S) {
  1855. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'');
  1856. };
  1857. this.UpperCase = function (s) {
  1858. return s.toUpperCase();
  1859. };
  1860. this.LowerCase = function (s) {
  1861. return s.toLowerCase();
  1862. };
  1863. this.CompareStr = function (s1, s2) {
  1864. var l1 = s1.length;
  1865. var l2 = s2.length;
  1866. if (l1<=l2){
  1867. var s = s2.substr(0,l1);
  1868. if (s1<s){ return -1;
  1869. } else if (s1>s){ return 1;
  1870. } else { return l1<l2 ? -1 : 0; };
  1871. } else {
  1872. var s = s1.substr(0,l2);
  1873. if (s<s2){ return -1;
  1874. } else { return 1; };
  1875. };
  1876. };
  1877. this.CompareText = function (s1, s2) {
  1878. var l1 = s1.toLowerCase();
  1879. var l2 = s2.toLowerCase();
  1880. if (l1>l2){ return 1;
  1881. } else if (l1<l2){ return -1;
  1882. } else { return 0; };
  1883. };
  1884. this.Format = function (Fmt, Args) {
  1885. var Result = "";
  1886. Result = $mod.Format$1(Fmt,Args,$mod.FormatSettings);
  1887. return Result;
  1888. };
  1889. this.Format$1 = function (Fmt, Args, aSettings) {
  1890. var Result = "";
  1891. var ChPos = 0;
  1892. var OldPos = 0;
  1893. var ArgPos = 0;
  1894. var DoArg = 0;
  1895. var Len = 0;
  1896. var Hs = "";
  1897. var ToAdd = "";
  1898. var Index = 0;
  1899. var Width = 0;
  1900. var Prec = 0;
  1901. var Left = false;
  1902. var Fchar = "";
  1903. var vq = 0;
  1904. function ReadFormat() {
  1905. var Result = "";
  1906. var Value = 0;
  1907. function ReadInteger() {
  1908. var Code = 0;
  1909. var ArgN = 0;
  1910. if (Value !== -1) return;
  1911. OldPos = ChPos;
  1912. while ((ChPos <= Len) && (Fmt.charAt(ChPos - 1) <= "9") && (Fmt.charAt(ChPos - 1) >= "0")) ChPos += 1;
  1913. if (ChPos > Len) $impl.DoFormatError(1,Fmt);
  1914. if (Fmt.charAt(ChPos - 1) === "*") {
  1915. if (Index === 255) {
  1916. ArgN = ArgPos}
  1917. else {
  1918. ArgN = Index;
  1919. Index += 1;
  1920. };
  1921. if ((ChPos > OldPos) || (ArgN > (rtl.length(Args) - 1))) $impl.DoFormatError(1,Fmt);
  1922. ArgPos = ArgN + 1;
  1923. var $tmp = Args[ArgN].VType;
  1924. if ($tmp === 0) {
  1925. Value = Args[ArgN].VJSValue}
  1926. else if ($tmp === 19) {
  1927. Value = Args[ArgN].VJSValue}
  1928. else {
  1929. $impl.DoFormatError(1,Fmt);
  1930. };
  1931. ChPos += 1;
  1932. } else {
  1933. if (OldPos < ChPos) {
  1934. pas.System.val(pas.System.Copy(Fmt,OldPos,ChPos - OldPos),{get: function () {
  1935. return Value;
  1936. }, set: function (v) {
  1937. Value = v;
  1938. }},{get: function () {
  1939. return Code;
  1940. }, set: function (v) {
  1941. Code = v;
  1942. }});
  1943. if (Code > 0) $impl.DoFormatError(1,Fmt);
  1944. } else Value = -1;
  1945. };
  1946. };
  1947. function ReadIndex() {
  1948. if (Fmt.charAt(ChPos - 1) !== ":") {
  1949. ReadInteger()}
  1950. else Value = 0;
  1951. if (Fmt.charAt(ChPos - 1) === ":") {
  1952. if (Value === -1) $impl.DoFormatError(2,Fmt);
  1953. Index = Value;
  1954. Value = -1;
  1955. ChPos += 1;
  1956. };
  1957. };
  1958. function ReadLeft() {
  1959. if (Fmt.charAt(ChPos - 1) === "-") {
  1960. Left = true;
  1961. ChPos += 1;
  1962. } else Left = false;
  1963. };
  1964. function ReadWidth() {
  1965. ReadInteger();
  1966. if (Value !== -1) {
  1967. Width = Value;
  1968. Value = -1;
  1969. };
  1970. };
  1971. function ReadPrec() {
  1972. if (Fmt.charAt(ChPos - 1) === ".") {
  1973. ChPos += 1;
  1974. ReadInteger();
  1975. if (Value === -1) Value = 0;
  1976. Prec = Value;
  1977. };
  1978. };
  1979. Index = 255;
  1980. Width = -1;
  1981. Prec = -1;
  1982. Value = -1;
  1983. ChPos += 1;
  1984. if (Fmt.charAt(ChPos - 1) === "%") {
  1985. Result = "%";
  1986. return Result;
  1987. };
  1988. ReadIndex();
  1989. ReadLeft();
  1990. ReadWidth();
  1991. ReadPrec();
  1992. Result = pas.System.upcase(Fmt.charAt(ChPos - 1));
  1993. return Result;
  1994. };
  1995. function Checkarg(AT, err) {
  1996. var Result = false;
  1997. Result = false;
  1998. if (Index === 255) {
  1999. DoArg = ArgPos}
  2000. else DoArg = Index;
  2001. ArgPos = DoArg + 1;
  2002. if ((DoArg > (rtl.length(Args) - 1)) || (Args[DoArg].VType !== AT)) {
  2003. if (err) $impl.DoFormatError(3,Fmt);
  2004. ArgPos -= 1;
  2005. return Result;
  2006. };
  2007. Result = true;
  2008. return Result;
  2009. };
  2010. Result = "";
  2011. Len = Fmt.length;
  2012. ChPos = 1;
  2013. OldPos = 1;
  2014. ArgPos = 0;
  2015. while (ChPos <= Len) {
  2016. while ((ChPos <= Len) && (Fmt.charAt(ChPos - 1) !== "%")) ChPos += 1;
  2017. if (ChPos > OldPos) Result = Result + pas.System.Copy(Fmt,OldPos,ChPos - OldPos);
  2018. if (ChPos < Len) {
  2019. Fchar = ReadFormat();
  2020. var $tmp = Fchar;
  2021. if ($tmp === "D") {
  2022. if (Checkarg(0,false)) {
  2023. ToAdd = $mod.IntToStr(Args[DoArg].VJSValue)}
  2024. else if (Checkarg(19,true)) ToAdd = $mod.IntToStr(Args[DoArg].VJSValue);
  2025. Width = Math.abs(Width);
  2026. Index = Prec - ToAdd.length;
  2027. if (ToAdd.charAt(0) !== "-") {
  2028. ToAdd = pas.System.StringOfChar("0",Index) + ToAdd}
  2029. else pas.System.Insert(pas.System.StringOfChar("0",Index + 1),{get: function () {
  2030. return ToAdd;
  2031. }, set: function (v) {
  2032. ToAdd = v;
  2033. }},2);
  2034. } else if ($tmp === "U") {
  2035. if (Checkarg(0,false)) {
  2036. ToAdd = $mod.IntToStr(Args[DoArg].VJSValue >>> 0)}
  2037. else if (Checkarg(19,true)) ToAdd = $mod.IntToStr(Args[DoArg].VJSValue);
  2038. Width = Math.abs(Width);
  2039. Index = Prec - ToAdd.length;
  2040. ToAdd = pas.System.StringOfChar("0",Index) + ToAdd;
  2041. } else if ($tmp === "E") {
  2042. if (Checkarg(12,false)) {
  2043. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,2,3,Prec,aSettings)}
  2044. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,2,3,Prec,aSettings);
  2045. } else if ($tmp === "F") {
  2046. if (Checkarg(12,false)) {
  2047. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,0,9999,Prec,aSettings)}
  2048. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,0,9999,Prec,aSettings);
  2049. } else if ($tmp === "G") {
  2050. if (Checkarg(12,false)) {
  2051. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,1,Prec,3,aSettings)}
  2052. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,1,Prec,3,aSettings);
  2053. } else if ($tmp === "N") {
  2054. if (Checkarg(12,false)) {
  2055. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,3,9999,Prec,aSettings)}
  2056. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,3,9999,Prec,aSettings);
  2057. } else if ($tmp === "M") {
  2058. if (Checkarg(12,false)) {
  2059. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,4,9999,Prec,aSettings)}
  2060. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,4,9999,Prec,aSettings);
  2061. } else if ($tmp === "S") {
  2062. if (Checkarg(18,false)) {
  2063. Hs = Args[DoArg].VJSValue}
  2064. else if (Checkarg(9,true)) Hs = Args[DoArg].VJSValue;
  2065. Index = Hs.length;
  2066. if ((Prec !== -1) && (Index > Prec)) Index = Prec;
  2067. ToAdd = pas.System.Copy(Hs,1,Index);
  2068. } else if ($tmp === "P") {
  2069. if (Checkarg(0,false)) {
  2070. ToAdd = $mod.IntToHex(Args[DoArg].VJSValue,8)}
  2071. else if (Checkarg(0,true)) ToAdd = $mod.IntToHex(Args[DoArg].VJSValue,16);
  2072. } else if ($tmp === "X") {
  2073. if (Checkarg(0,false)) {
  2074. vq = Args[DoArg].VJSValue;
  2075. Index = 16;
  2076. } else if (Checkarg(19,true)) {
  2077. vq = Args[DoArg].VJSValue;
  2078. Index = 31;
  2079. };
  2080. if (Prec > Index) {
  2081. ToAdd = $mod.IntToHex(vq,Index)}
  2082. else {
  2083. Index = 1;
  2084. while ((rtl.shl(1,Index * 4) <= vq) && (Index < 16)) Index += 1;
  2085. if (Index > Prec) Prec = Index;
  2086. ToAdd = $mod.IntToHex(vq,Prec);
  2087. };
  2088. } else if ($tmp === "%") ToAdd = "%";
  2089. if (Width !== -1) if (ToAdd.length < Width) if (!Left) {
  2090. ToAdd = pas.System.StringOfChar(" ",Width - ToAdd.length) + ToAdd}
  2091. else ToAdd = ToAdd + pas.System.StringOfChar(" ",Width - ToAdd.length);
  2092. Result = Result + ToAdd;
  2093. };
  2094. ChPos += 1;
  2095. OldPos = ChPos;
  2096. };
  2097. return Result;
  2098. };
  2099. var Alpha = rtl.createSet(null,65,90,null,97,122,95);
  2100. var AlphaNum = rtl.unionSet(Alpha,rtl.createSet(null,48,57));
  2101. var Dot = ".";
  2102. this.IsValidIdent = function (Ident, AllowDots, StrictDots) {
  2103. var Result = false;
  2104. var First = false;
  2105. var I = 0;
  2106. var Len = 0;
  2107. Len = Ident.length;
  2108. if (Len < 1) return false;
  2109. First = true;
  2110. Result = false;
  2111. I = 1;
  2112. while (I <= Len) {
  2113. if (First) {
  2114. if (!(Ident.charCodeAt(I - 1) in Alpha)) return Result;
  2115. First = false;
  2116. } else if (AllowDots && (Ident.charAt(I - 1) === Dot)) {
  2117. if (StrictDots) {
  2118. if (I >= Len) return Result;
  2119. First = true;
  2120. };
  2121. } else if (!(Ident.charCodeAt(I - 1) in AlphaNum)) return Result;
  2122. I = I + 1;
  2123. };
  2124. Result = true;
  2125. return Result;
  2126. };
  2127. this.IntToStr = function (Value) {
  2128. var Result = "";
  2129. Result = "" + Value;
  2130. return Result;
  2131. };
  2132. this.TryStrToInt$2 = function (S, res) {
  2133. var Result = false;
  2134. Result = $impl.IntTryStrToInt(S,res,$mod.FormatSettings.DecimalSeparator);
  2135. return Result;
  2136. };
  2137. this.StrToInt = function (S) {
  2138. var Result = 0;
  2139. var R = 0;
  2140. if (!$mod.TryStrToInt$2(S,{get: function () {
  2141. return R;
  2142. }, set: function (v) {
  2143. R = v;
  2144. }})) throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SErrInvalidInteger"),pas.System.VarRecs(18,S)]);
  2145. Result = R;
  2146. return Result;
  2147. };
  2148. this.IntToHex = function (Value, Digits) {
  2149. var Result = "";
  2150. Result = "";
  2151. if (Value < 0) if (Value<0) Value = 0xFFFFFFFF + Value + 1;
  2152. Result=Value.toString(16);
  2153. Result = $mod.UpperCase(Result);
  2154. while (Result.length < Digits) Result = "0" + Result;
  2155. return Result;
  2156. };
  2157. this.TFloatFormat = {"0": "ffFixed", ffFixed: 0, "1": "ffGeneral", ffGeneral: 1, "2": "ffExponent", ffExponent: 2, "3": "ffNumber", ffNumber: 3, "4": "ffCurrency", ffCurrency: 4};
  2158. this.FloatToStrF$1 = function (Value, format, Precision, Digits, aSettings) {
  2159. var Result = "";
  2160. var TS = "";
  2161. var DS = "";
  2162. DS = aSettings.DecimalSeparator;
  2163. TS = aSettings.ThousandSeparator;
  2164. var $tmp = format;
  2165. if ($tmp === 1) {
  2166. Result = $impl.FormatGeneralFloat(Value,Precision,DS)}
  2167. else if ($tmp === 2) {
  2168. Result = $impl.FormatExponentFloat(Value,Precision,Digits,DS)}
  2169. else if ($tmp === 0) {
  2170. Result = $impl.FormatFixedFloat(Value,Digits,DS)}
  2171. else if ($tmp === 3) {
  2172. Result = $impl.FormatNumberFloat(Value,Digits,DS,TS)}
  2173. else if ($tmp === 4) Result = $impl.FormatNumberCurrency(Value * 10000,Digits,aSettings);
  2174. if ((format !== 4) && (Result.length > 1) && (Result.charAt(0) === "-")) $impl.RemoveLeadingNegativeSign({get: function () {
  2175. return Result;
  2176. }, set: function (v) {
  2177. Result = v;
  2178. }},DS,TS);
  2179. return Result;
  2180. };
  2181. this.OnGetEnvironmentVariable = null;
  2182. this.OnGetEnvironmentString = null;
  2183. this.OnGetEnvironmentVariableCount = null;
  2184. this.GetEnvironmentVariable = function (EnvVar) {
  2185. var Result = "";
  2186. if ($mod.OnGetEnvironmentVariable != null) {
  2187. Result = $mod.OnGetEnvironmentVariable(EnvVar)}
  2188. else Result = "";
  2189. return Result;
  2190. };
  2191. this.GetEnvironmentVariableCount = function () {
  2192. var Result = 0;
  2193. if ($mod.OnGetEnvironmentVariableCount != null) {
  2194. Result = $mod.OnGetEnvironmentVariableCount()}
  2195. else Result = 0;
  2196. return Result;
  2197. };
  2198. this.GetEnvironmentString = function (Index) {
  2199. var Result = "";
  2200. if ($mod.OnGetEnvironmentString != null) {
  2201. Result = $mod.OnGetEnvironmentString(Index)}
  2202. else Result = "";
  2203. return Result;
  2204. };
  2205. this.TimeSeparator = "";
  2206. this.DateSeparator = "";
  2207. this.ShortDateFormat = "";
  2208. this.LongDateFormat = "";
  2209. this.ShortTimeFormat = "";
  2210. this.LongTimeFormat = "";
  2211. this.DecimalSeparator = "";
  2212. this.ThousandSeparator = "";
  2213. this.TimeAMString = "";
  2214. this.TimePMString = "";
  2215. this.ShortMonthNames = rtl.arraySetLength(null,"",12);
  2216. this.LongMonthNames = rtl.arraySetLength(null,"",12);
  2217. this.ShortDayNames = rtl.arraySetLength(null,"",7);
  2218. this.LongDayNames = rtl.arraySetLength(null,"",7);
  2219. this.FormatSettings = this.TFormatSettings.$new();
  2220. this.CurrencyFormat = 0;
  2221. this.NegCurrFormat = 0;
  2222. this.CurrencyDecimals = 0;
  2223. this.CurrencyString = "";
  2224. $mod.$implcode = function () {
  2225. $impl.DefaultShortMonthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  2226. $impl.DefaultLongMonthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  2227. $impl.DefaultShortDayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  2228. $impl.DefaultLongDayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
  2229. $impl.feInvalidFormat = 1;
  2230. $impl.feMissingArgument = 2;
  2231. $impl.feInvalidArgIndex = 3;
  2232. $impl.DoFormatError = function (ErrCode, fmt) {
  2233. var $tmp = ErrCode;
  2234. if ($tmp === 1) {
  2235. throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SInvalidFormat"),pas.System.VarRecs(18,fmt)])}
  2236. else if ($tmp === 2) {
  2237. throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SArgumentMissing"),pas.System.VarRecs(18,fmt)])}
  2238. else if ($tmp === 3) throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SInvalidArgIndex"),pas.System.VarRecs(18,fmt)]);
  2239. };
  2240. $impl.maxdigits = 15;
  2241. $impl.ReplaceDecimalSep = function (S, DS) {
  2242. var Result = "";
  2243. var P = 0;
  2244. P = pas.System.Pos(".",S);
  2245. if (P > 0) {
  2246. Result = pas.System.Copy(S,1,P - 1) + DS + pas.System.Copy(S,P + 1,S.length - P)}
  2247. else Result = S;
  2248. return Result;
  2249. };
  2250. $impl.FormatGeneralFloat = function (Value, Precision, DS) {
  2251. var Result = "";
  2252. var P = 0;
  2253. var PE = 0;
  2254. var Q = 0;
  2255. var Exponent = 0;
  2256. if ((Precision === -1) || (Precision > 15)) Precision = 15;
  2257. Result = rtl.floatToStr(Value,Precision + 7);
  2258. Result = $mod.TrimLeft(Result);
  2259. P = pas.System.Pos(".",Result);
  2260. if (P === 0) return Result;
  2261. PE = pas.System.Pos("E",Result);
  2262. if (PE === 0) {
  2263. Result = $impl.ReplaceDecimalSep(Result,DS);
  2264. return Result;
  2265. };
  2266. Q = PE + 2;
  2267. Exponent = 0;
  2268. while (Q <= Result.length) {
  2269. Exponent = ((Exponent * 10) + Result.charCodeAt(Q - 1)) - 48;
  2270. Q += 1;
  2271. };
  2272. if (Result.charAt((PE + 1) - 1) === "-") Exponent = -Exponent;
  2273. if (((P + Exponent) < PE) && (Exponent > -6)) {
  2274. Result = rtl.strSetLength(Result,PE - 1);
  2275. if (Exponent >= 0) {
  2276. for (var $l = 0, $end = Exponent - 1; $l <= $end; $l++) {
  2277. Q = $l;
  2278. Result = rtl.setCharAt(Result,P - 1,Result.charAt((P + 1) - 1));
  2279. P += 1;
  2280. };
  2281. Result = rtl.setCharAt(Result,P - 1,".");
  2282. P = 1;
  2283. if (Result.charAt(P - 1) === "-") P += 1;
  2284. while ((Result.charAt(P - 1) === "0") && (P < Result.length) && (pas.System.Copy(Result,P + 1,DS.length) !== DS)) pas.System.Delete({get: function () {
  2285. return Result;
  2286. }, set: function (v) {
  2287. Result = v;
  2288. }},P,1);
  2289. } else {
  2290. pas.System.Insert(pas.System.Copy("00000",1,-Exponent),{get: function () {
  2291. return Result;
  2292. }, set: function (v) {
  2293. Result = v;
  2294. }},P - 1);
  2295. Result = rtl.setCharAt(Result,P - Exponent - 1,Result.charAt(P - Exponent - 1 - 1));
  2296. Result = rtl.setCharAt(Result,P - 1,".");
  2297. if (Exponent !== -1) Result = rtl.setCharAt(Result,P - Exponent - 1 - 1,"0");
  2298. };
  2299. Q = Result.length;
  2300. while ((Q > 0) && (Result.charAt(Q - 1) === "0")) Q -= 1;
  2301. if (Result.charAt(Q - 1) === ".") Q -= 1;
  2302. if ((Q === 0) || ((Q === 1) && (Result.charAt(0) === "-"))) {
  2303. Result = "0"}
  2304. else Result = rtl.strSetLength(Result,Q);
  2305. } else {
  2306. while (Result.charAt(PE - 1 - 1) === "0") {
  2307. pas.System.Delete({get: function () {
  2308. return Result;
  2309. }, set: function (v) {
  2310. Result = v;
  2311. }},PE - 1,1);
  2312. PE -= 1;
  2313. };
  2314. if (Result.charAt(PE - 1 - 1) === DS) {
  2315. pas.System.Delete({get: function () {
  2316. return Result;
  2317. }, set: function (v) {
  2318. Result = v;
  2319. }},PE - 1,1);
  2320. PE -= 1;
  2321. };
  2322. if (Result.charAt((PE + 1) - 1) === "+") {
  2323. pas.System.Delete({get: function () {
  2324. return Result;
  2325. }, set: function (v) {
  2326. Result = v;
  2327. }},PE + 1,1)}
  2328. else PE += 1;
  2329. while (Result.charAt((PE + 1) - 1) === "0") pas.System.Delete({get: function () {
  2330. return Result;
  2331. }, set: function (v) {
  2332. Result = v;
  2333. }},PE + 1,1);
  2334. };
  2335. Result = $impl.ReplaceDecimalSep(Result,DS);
  2336. return Result;
  2337. };
  2338. $impl.FormatExponentFloat = function (Value, Precision, Digits, DS) {
  2339. var Result = "";
  2340. var P = 0;
  2341. DS = $mod.FormatSettings.DecimalSeparator;
  2342. if ((Precision === -1) || (Precision > 15)) Precision = 15;
  2343. Result = rtl.floatToStr(Value,Precision + 7);
  2344. while (Result.charAt(0) === " ") pas.System.Delete({get: function () {
  2345. return Result;
  2346. }, set: function (v) {
  2347. Result = v;
  2348. }},1,1);
  2349. P = pas.System.Pos("E",Result);
  2350. if (P === 0) {
  2351. Result = $impl.ReplaceDecimalSep(Result,DS);
  2352. return Result;
  2353. };
  2354. P += 2;
  2355. if (Digits > 4) Digits = 4;
  2356. Digits = (Result.length - P - Digits) + 1;
  2357. if (Digits < 0) {
  2358. pas.System.Insert(pas.System.Copy("0000",1,-Digits),{get: function () {
  2359. return Result;
  2360. }, set: function (v) {
  2361. Result = v;
  2362. }},P)}
  2363. else while ((Digits > 0) && (Result.charAt(P - 1) === "0")) {
  2364. pas.System.Delete({get: function () {
  2365. return Result;
  2366. }, set: function (v) {
  2367. Result = v;
  2368. }},P,1);
  2369. if (P > Result.length) {
  2370. pas.System.Delete({get: function () {
  2371. return Result;
  2372. }, set: function (v) {
  2373. Result = v;
  2374. }},P - 2,2);
  2375. break;
  2376. };
  2377. Digits -= 1;
  2378. };
  2379. Result = $impl.ReplaceDecimalSep(Result,DS);
  2380. return Result;
  2381. };
  2382. $impl.FormatFixedFloat = function (Value, Digits, DS) {
  2383. var Result = "";
  2384. if (Digits === -1) {
  2385. Digits = 2}
  2386. else if (Digits > 18) Digits = 18;
  2387. Result = rtl.floatToStr(Value,0,Digits);
  2388. if ((Result !== "") && (Result.charAt(0) === " ")) pas.System.Delete({get: function () {
  2389. return Result;
  2390. }, set: function (v) {
  2391. Result = v;
  2392. }},1,1);
  2393. Result = $impl.ReplaceDecimalSep(Result,DS);
  2394. return Result;
  2395. };
  2396. $impl.FormatNumberFloat = function (Value, Digits, DS, TS) {
  2397. var Result = "";
  2398. var P = 0;
  2399. if (Digits === -1) {
  2400. Digits = 2}
  2401. else if (Digits > 15) Digits = 15;
  2402. Result = rtl.floatToStr(Value,0,Digits);
  2403. if ((Result !== "") && (Result.charAt(0) === " ")) pas.System.Delete({get: function () {
  2404. return Result;
  2405. }, set: function (v) {
  2406. Result = v;
  2407. }},1,1);
  2408. P = pas.System.Pos(".",Result);
  2409. if (P <= 0) P = Result.length + 1;
  2410. Result = $impl.ReplaceDecimalSep(Result,DS);
  2411. P -= 3;
  2412. if ((TS !== "") && (TS !== "\x00")) while (P > 1) {
  2413. if (Result.charAt(P - 1 - 1) !== "-") pas.System.Insert(TS,{get: function () {
  2414. return Result;
  2415. }, set: function (v) {
  2416. Result = v;
  2417. }},P);
  2418. P -= 3;
  2419. };
  2420. return Result;
  2421. };
  2422. $impl.RemoveLeadingNegativeSign = function (AValue, DS, aThousandSeparator) {
  2423. var Result = false;
  2424. var i = 0;
  2425. var TS = "";
  2426. var StartPos = 0;
  2427. Result = false;
  2428. StartPos = 2;
  2429. TS = aThousandSeparator;
  2430. for (var $l = StartPos, $end = AValue.get().length; $l <= $end; $l++) {
  2431. i = $l;
  2432. Result = (AValue.get().charCodeAt(i - 1) in rtl.createSet(48,DS.charCodeAt(),69,43)) || (AValue.get().charAt(i - 1) === TS);
  2433. if (!Result) break;
  2434. };
  2435. if (Result && (AValue.get().charAt(0) === "-")) pas.System.Delete(AValue,1,1);
  2436. return Result;
  2437. };
  2438. $impl.FormatNumberCurrency = function (Value, Digits, aSettings) {
  2439. var Result = "";
  2440. var Negative = false;
  2441. var P = 0;
  2442. var CS = "";
  2443. var DS = "";
  2444. var TS = "";
  2445. DS = aSettings.DecimalSeparator;
  2446. TS = aSettings.ThousandSeparator;
  2447. CS = aSettings.CurrencyString;
  2448. if (Digits === -1) {
  2449. Digits = aSettings.CurrencyDecimals}
  2450. else if (Digits > 18) Digits = 18;
  2451. Result = rtl.floatToStr(Value / 10000,0,Digits);
  2452. Negative = Result.charAt(0) === "-";
  2453. if (Negative) pas.System.Delete({get: function () {
  2454. return Result;
  2455. }, set: function (v) {
  2456. Result = v;
  2457. }},1,1);
  2458. P = pas.System.Pos(".",Result);
  2459. if (TS !== "") {
  2460. if (P !== 0) {
  2461. Result = $impl.ReplaceDecimalSep(Result,DS)}
  2462. else P = Result.length + 1;
  2463. P -= 3;
  2464. while (P > 1) {
  2465. pas.System.Insert(TS,{get: function () {
  2466. return Result;
  2467. }, set: function (v) {
  2468. Result = v;
  2469. }},P);
  2470. P -= 3;
  2471. };
  2472. };
  2473. if (Negative) $impl.RemoveLeadingNegativeSign({get: function () {
  2474. return Result;
  2475. }, set: function (v) {
  2476. Result = v;
  2477. }},DS,TS);
  2478. if (!Negative) {
  2479. var $tmp = aSettings.CurrencyFormat;
  2480. if ($tmp === 0) {
  2481. Result = CS + Result}
  2482. else if ($tmp === 1) {
  2483. Result = Result + CS}
  2484. else if ($tmp === 2) {
  2485. Result = CS + " " + Result}
  2486. else if ($tmp === 3) Result = Result + " " + CS;
  2487. } else {
  2488. var $tmp1 = aSettings.NegCurrFormat;
  2489. if ($tmp1 === 0) {
  2490. Result = "(" + CS + Result + ")"}
  2491. else if ($tmp1 === 1) {
  2492. Result = "-" + CS + Result}
  2493. else if ($tmp1 === 2) {
  2494. Result = CS + "-" + Result}
  2495. else if ($tmp1 === 3) {
  2496. Result = CS + Result + "-"}
  2497. else if ($tmp1 === 4) {
  2498. Result = "(" + Result + CS + ")"}
  2499. else if ($tmp1 === 5) {
  2500. Result = "-" + Result + CS}
  2501. else if ($tmp1 === 6) {
  2502. Result = Result + "-" + CS}
  2503. else if ($tmp1 === 7) {
  2504. Result = Result + CS + "-"}
  2505. else if ($tmp1 === 8) {
  2506. Result = "-" + Result + " " + CS}
  2507. else if ($tmp1 === 9) {
  2508. Result = "-" + CS + " " + Result}
  2509. else if ($tmp1 === 10) {
  2510. Result = Result + " " + CS + "-"}
  2511. else if ($tmp1 === 11) {
  2512. Result = CS + " " + Result + "-"}
  2513. else if ($tmp1 === 12) {
  2514. Result = CS + " " + "-" + Result}
  2515. else if ($tmp1 === 13) {
  2516. Result = Result + "-" + " " + CS}
  2517. else if ($tmp1 === 14) {
  2518. Result = "(" + CS + " " + Result + ")"}
  2519. else if ($tmp1 === 15) Result = "(" + Result + " " + CS + ")";
  2520. };
  2521. return Result;
  2522. };
  2523. $impl.IntTryStrToInt = function (S, res, aSep) {
  2524. var Result = false;
  2525. var Radix = 10;
  2526. var N = "";
  2527. var J = undefined;
  2528. N = S;
  2529. if ((pas.System.Pos(aSep,N) !== 0) || (pas.System.Pos(".",N) !== 0)) return false;
  2530. var $tmp = pas.System.Copy(N,1,1);
  2531. if ($tmp === "$") {
  2532. Radix = 16}
  2533. else if ($tmp === "&") {
  2534. Radix = 8}
  2535. else if ($tmp === "%") Radix = 2;
  2536. if ((Radix !== 16) && (pas.System.Pos("e",$mod.LowerCase(N)) !== 0)) return false;
  2537. if (Radix !== 10) pas.System.Delete({get: function () {
  2538. return N;
  2539. }, set: function (v) {
  2540. N = v;
  2541. }},1,1);
  2542. J = parseInt(N,Radix);
  2543. Result = !isNaN(J);
  2544. if (Result) res.set(rtl.trunc(J));
  2545. return Result;
  2546. };
  2547. $impl.InitGlobalFormatSettings = function () {
  2548. $mod.FormatSettings.$assign($mod.TFormatSettings.Create());
  2549. $mod.TimeSeparator = $mod.FormatSettings.TimeSeparator;
  2550. $mod.DateSeparator = $mod.FormatSettings.DateSeparator;
  2551. $mod.ShortDateFormat = $mod.FormatSettings.ShortDateFormat;
  2552. $mod.LongDateFormat = $mod.FormatSettings.LongDateFormat;
  2553. $mod.ShortTimeFormat = $mod.FormatSettings.ShortTimeFormat;
  2554. $mod.LongTimeFormat = $mod.FormatSettings.LongTimeFormat;
  2555. $mod.DecimalSeparator = $mod.FormatSettings.DecimalSeparator;
  2556. $mod.ThousandSeparator = $mod.FormatSettings.ThousandSeparator;
  2557. $mod.TimeAMString = $mod.FormatSettings.TimeAMString;
  2558. $mod.TimePMString = $mod.FormatSettings.TimePMString;
  2559. $mod.CurrencyFormat = $mod.FormatSettings.CurrencyFormat;
  2560. $mod.NegCurrFormat = $mod.FormatSettings.NegCurrFormat;
  2561. $mod.CurrencyDecimals = $mod.FormatSettings.CurrencyDecimals;
  2562. $mod.CurrencyString = $mod.FormatSettings.CurrencyString;
  2563. };
  2564. $impl.DoClassRef = function (C) {
  2565. if (C === null) ;
  2566. };
  2567. };
  2568. $mod.$init = function () {
  2569. (function () {
  2570. $impl.InitGlobalFormatSettings();
  2571. })();
  2572. $impl.DoClassRef($mod.EInvalidCast);
  2573. $impl.DoClassRef($mod.EAbstractError);
  2574. $impl.DoClassRef($mod.ERangeError);
  2575. $mod.ShortMonthNames = $impl.DefaultShortMonthNames.slice(0);
  2576. $mod.LongMonthNames = $impl.DefaultLongMonthNames.slice(0);
  2577. $mod.ShortDayNames = $impl.DefaultShortDayNames.slice(0);
  2578. $mod.LongDayNames = $impl.DefaultLongDayNames.slice(0);
  2579. };
  2580. },[]);
  2581. rtl.module("Classes",["System","RTLConsts","Types","SysUtils","JS"],function () {
  2582. "use strict";
  2583. var $mod = this;
  2584. var $impl = $mod.$impl;
  2585. rtl.createClass(this,"EListError",pas.SysUtils.Exception,function () {
  2586. });
  2587. rtl.createClass(this,"EStringListError",this.EListError,function () {
  2588. });
  2589. rtl.createClass(this,"EComponentError",pas.SysUtils.Exception,function () {
  2590. });
  2591. rtl.createClass(this,"TFPList",pas.System.TObject,function () {
  2592. this.$init = function () {
  2593. pas.System.TObject.$init.call(this);
  2594. this.FList = [];
  2595. this.FCount = 0;
  2596. this.FCapacity = 0;
  2597. };
  2598. this.$final = function () {
  2599. this.FList = undefined;
  2600. pas.System.TObject.$final.call(this);
  2601. };
  2602. this.Get = function (Index) {
  2603. var Result = undefined;
  2604. if ((Index < 0) || (Index >= this.FCount)) this.RaiseIndexError(Index);
  2605. Result = this.FList[Index];
  2606. return Result;
  2607. };
  2608. this.SetCapacity = function (NewCapacity) {
  2609. if (NewCapacity < this.FCount) this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListCapacityError"),"" + NewCapacity);
  2610. if (NewCapacity === this.FCapacity) return;
  2611. this.FList = rtl.arraySetLength(this.FList,undefined,NewCapacity);
  2612. this.FCapacity = NewCapacity;
  2613. };
  2614. this.SetCount = function (NewCount) {
  2615. if (NewCount < 0) this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListCountError"),"" + NewCount);
  2616. if (NewCount > this.FCount) {
  2617. if (NewCount > this.FCapacity) this.SetCapacity(NewCount);
  2618. };
  2619. this.FCount = NewCount;
  2620. };
  2621. this.RaiseIndexError = function (Index) {
  2622. this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),"" + Index);
  2623. };
  2624. this.Destroy = function () {
  2625. this.Clear();
  2626. pas.System.TObject.Destroy.call(this);
  2627. };
  2628. this.Add = function (Item) {
  2629. var Result = 0;
  2630. if (this.FCount === this.FCapacity) this.Expand();
  2631. this.FList[this.FCount] = Item;
  2632. Result = this.FCount;
  2633. this.FCount += 1;
  2634. return Result;
  2635. };
  2636. this.Clear = function () {
  2637. if (rtl.length(this.FList) > 0) {
  2638. this.SetCount(0);
  2639. this.SetCapacity(0);
  2640. };
  2641. };
  2642. this.Delete = function (Index) {
  2643. if ((Index < 0) || (Index >= this.FCount)) this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),"" + Index);
  2644. this.FCount = this.FCount - 1;
  2645. this.FList.splice(Index,1);
  2646. this.FCapacity -= 1;
  2647. };
  2648. this.Error = function (Msg, Data) {
  2649. throw $mod.EListError.$create("CreateFmt",[Msg,pas.System.VarRecs(18,Data)]);
  2650. };
  2651. this.Expand = function () {
  2652. var Result = null;
  2653. var IncSize = 0;
  2654. if (this.FCount < this.FCapacity) return this;
  2655. IncSize = 4;
  2656. if (this.FCapacity > 3) IncSize = IncSize + 4;
  2657. if (this.FCapacity > 8) IncSize = IncSize + 8;
  2658. if (this.FCapacity > 127) IncSize += this.FCapacity >>> 2;
  2659. this.SetCapacity(this.FCapacity + IncSize);
  2660. Result = this;
  2661. return Result;
  2662. };
  2663. this.IndexOf = function (Item) {
  2664. var Result = 0;
  2665. var C = 0;
  2666. Result = 0;
  2667. C = this.FCount;
  2668. while ((Result < C) && (this.FList[Result] != Item)) Result += 1;
  2669. if (Result >= C) Result = -1;
  2670. return Result;
  2671. };
  2672. this.Last = function () {
  2673. var Result = undefined;
  2674. if (this.FCount === 0) {
  2675. Result = null}
  2676. else Result = this.Get(this.FCount - 1);
  2677. return Result;
  2678. };
  2679. this.Remove = function (Item) {
  2680. var Result = 0;
  2681. Result = this.IndexOf(Item);
  2682. if (Result !== -1) this.Delete(Result);
  2683. return Result;
  2684. };
  2685. });
  2686. rtl.createClass(this,"TPersistent",pas.System.TObject,function () {
  2687. });
  2688. rtl.createClass(this,"TStrings",this.TPersistent,function () {
  2689. this.$init = function () {
  2690. $mod.TPersistent.$init.call(this);
  2691. this.FSpecialCharsInited = false;
  2692. this.FAlwaysQuote = false;
  2693. this.FQuoteChar = "";
  2694. this.FDelimiter = "";
  2695. this.FNameValueSeparator = "";
  2696. this.FUpdateCount = 0;
  2697. this.FLBS = 0;
  2698. this.FSkipLastLineBreak = false;
  2699. this.FLineBreak = "";
  2700. };
  2701. this.SetValue = function (Name, Value) {
  2702. var L = 0;
  2703. this.CheckSpecialChars();
  2704. L = this.IndexOfName(Name);
  2705. if (L === -1) {
  2706. this.Add(Name + this.FNameValueSeparator + Value)}
  2707. else this.Put(L,Name + this.FNameValueSeparator + Value);
  2708. };
  2709. this.GetSkipLastLineBreak = function () {
  2710. var Result = false;
  2711. this.CheckSpecialChars();
  2712. Result = this.FSkipLastLineBreak;
  2713. return Result;
  2714. };
  2715. this.Error = function (Msg, Data) {
  2716. throw $mod.EStringListError.$create("CreateFmt",[Msg,pas.System.VarRecs(18,pas.SysUtils.IntToStr(Data))]);
  2717. };
  2718. this.GetCapacity = function () {
  2719. var Result = 0;
  2720. Result = this.GetCount();
  2721. return Result;
  2722. };
  2723. this.GetObject = function (Index) {
  2724. var Result = null;
  2725. if (Index === 0) ;
  2726. Result = null;
  2727. return Result;
  2728. };
  2729. this.GetTextStr = function () {
  2730. var Result = "";
  2731. var I = 0;
  2732. var S = "";
  2733. var NL = "";
  2734. this.CheckSpecialChars();
  2735. if (this.FLineBreak !== pas.System.sLineBreak) {
  2736. NL = this.FLineBreak}
  2737. else {
  2738. var $tmp = this.FLBS;
  2739. if ($tmp === 0) {
  2740. NL = "\n"}
  2741. else if ($tmp === 1) {
  2742. NL = "\r\n"}
  2743. else if ($tmp === 2) NL = "\r";
  2744. };
  2745. Result = "";
  2746. for (var $l = 0, $end = this.GetCount() - 1; $l <= $end; $l++) {
  2747. I = $l;
  2748. S = this.Get(I);
  2749. Result = Result + S;
  2750. if ((I < (this.GetCount() - 1)) || !this.GetSkipLastLineBreak()) Result = Result + NL;
  2751. };
  2752. return Result;
  2753. };
  2754. this.Put = function (Index, S) {
  2755. var Obj = null;
  2756. Obj = this.GetObject(Index);
  2757. this.Delete(Index);
  2758. this.InsertObject(Index,S,Obj);
  2759. };
  2760. this.PutObject = function (Index, AObject) {
  2761. if (Index === 0) return;
  2762. if (AObject === null) return;
  2763. };
  2764. this.DoCompareText = function (s1, s2) {
  2765. var Result = 0;
  2766. Result = pas.SysUtils.CompareText(s1,s2);
  2767. return Result;
  2768. };
  2769. this.CheckSpecialChars = function () {
  2770. if (!this.FSpecialCharsInited) {
  2771. this.FQuoteChar = '"';
  2772. this.FDelimiter = ",";
  2773. this.FNameValueSeparator = "=";
  2774. this.FLBS = pas.System.DefaultTextLineBreakStyle;
  2775. this.FSpecialCharsInited = true;
  2776. this.FLineBreak = pas.System.sLineBreak;
  2777. };
  2778. };
  2779. this.Create$1 = function () {
  2780. pas.System.TObject.Create.call(this);
  2781. this.FAlwaysQuote = false;
  2782. return this;
  2783. };
  2784. this.Destroy = function () {
  2785. pas.System.TObject.Destroy.call(this);
  2786. };
  2787. this.Add = function (S) {
  2788. var Result = 0;
  2789. Result = this.GetCount();
  2790. this.Insert(this.GetCount(),S);
  2791. return Result;
  2792. };
  2793. this.IndexOf = function (S) {
  2794. var Result = 0;
  2795. Result = 0;
  2796. while ((Result < this.GetCount()) && (this.DoCompareText(this.Get(Result),S) !== 0)) Result = Result + 1;
  2797. if (Result === this.GetCount()) Result = -1;
  2798. return Result;
  2799. };
  2800. this.IndexOfName = function (Name) {
  2801. var Result = 0;
  2802. var len = 0;
  2803. var S = "";
  2804. this.CheckSpecialChars();
  2805. Result = 0;
  2806. while (Result < this.GetCount()) {
  2807. S = this.Get(Result);
  2808. len = pas.System.Pos(this.FNameValueSeparator,S) - 1;
  2809. if ((len >= 0) && (this.DoCompareText(Name,pas.System.Copy(S,1,len)) === 0)) return Result;
  2810. Result += 1;
  2811. };
  2812. Result = -1;
  2813. return Result;
  2814. };
  2815. this.InsertObject = function (Index, S, AObject) {
  2816. this.Insert(Index,S);
  2817. this.PutObject(Index,AObject);
  2818. };
  2819. });
  2820. rtl.recNewT(this,"TStringItem",function () {
  2821. this.FString = "";
  2822. this.FObject = null;
  2823. this.$eq = function (b) {
  2824. return (this.FString === b.FString) && (this.FObject === b.FObject);
  2825. };
  2826. this.$assign = function (s) {
  2827. this.FString = s.FString;
  2828. this.FObject = s.FObject;
  2829. return this;
  2830. };
  2831. });
  2832. this.TStringsSortStyle = {"0": "sslNone", sslNone: 0, "1": "sslUser", sslUser: 1, "2": "sslAuto", sslAuto: 2};
  2833. rtl.createClass(this,"TStringList",this.TStrings,function () {
  2834. this.$init = function () {
  2835. $mod.TStrings.$init.call(this);
  2836. this.FList = [];
  2837. this.FCount = 0;
  2838. this.FOnChange = null;
  2839. this.FOnChanging = null;
  2840. this.FDuplicates = 0;
  2841. this.FCaseSensitive = false;
  2842. this.FOwnsObjects = false;
  2843. this.FSortStyle = 0;
  2844. };
  2845. this.$final = function () {
  2846. this.FList = undefined;
  2847. this.FOnChange = undefined;
  2848. this.FOnChanging = undefined;
  2849. $mod.TStrings.$final.call(this);
  2850. };
  2851. this.GetSorted = function () {
  2852. var Result = false;
  2853. Result = this.FSortStyle in rtl.createSet(1,2);
  2854. return Result;
  2855. };
  2856. this.Grow = function () {
  2857. var NC = 0;
  2858. NC = this.GetCapacity();
  2859. if (NC >= 256) {
  2860. NC = NC + rtl.trunc(NC / 4)}
  2861. else if (NC === 0) {
  2862. NC = 4}
  2863. else NC = NC * 4;
  2864. this.SetCapacity(NC);
  2865. };
  2866. this.InternalClear = function (FromIndex, ClearOnly) {
  2867. var I = 0;
  2868. if (FromIndex < this.FCount) {
  2869. if (this.FOwnsObjects) {
  2870. for (var $l = FromIndex, $end = this.FCount - 1; $l <= $end; $l++) {
  2871. I = $l;
  2872. this.FList[I].FString = "";
  2873. pas.SysUtils.FreeAndNil({p: this.FList[I], get: function () {
  2874. return this.p.FObject;
  2875. }, set: function (v) {
  2876. this.p.FObject = v;
  2877. }});
  2878. };
  2879. } else {
  2880. for (var $l1 = FromIndex, $end1 = this.FCount - 1; $l1 <= $end1; $l1++) {
  2881. I = $l1;
  2882. this.FList[I].FString = "";
  2883. };
  2884. };
  2885. this.FCount = FromIndex;
  2886. };
  2887. if (!ClearOnly) this.SetCapacity(0);
  2888. };
  2889. this.CheckIndex = function (AIndex) {
  2890. if ((AIndex < 0) || (AIndex >= this.FCount)) this.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),AIndex);
  2891. };
  2892. this.Changed = function () {
  2893. if (this.FUpdateCount === 0) {
  2894. if (this.FOnChange != null) this.FOnChange(this);
  2895. };
  2896. };
  2897. this.Changing = function () {
  2898. if (this.FUpdateCount === 0) if (this.FOnChanging != null) this.FOnChanging(this);
  2899. };
  2900. this.Get = function (Index) {
  2901. var Result = "";
  2902. this.CheckIndex(Index);
  2903. Result = this.FList[Index].FString;
  2904. return Result;
  2905. };
  2906. this.GetCapacity = function () {
  2907. var Result = 0;
  2908. Result = rtl.length(this.FList);
  2909. return Result;
  2910. };
  2911. this.GetCount = function () {
  2912. var Result = 0;
  2913. Result = this.FCount;
  2914. return Result;
  2915. };
  2916. this.GetObject = function (Index) {
  2917. var Result = null;
  2918. this.CheckIndex(Index);
  2919. Result = this.FList[Index].FObject;
  2920. return Result;
  2921. };
  2922. this.Put = function (Index, S) {
  2923. if (this.GetSorted()) this.Error(rtl.getResStr(pas.RTLConsts,"SSortedListError"),0);
  2924. this.CheckIndex(Index);
  2925. this.Changing();
  2926. this.FList[Index].FString = S;
  2927. this.Changed();
  2928. };
  2929. this.PutObject = function (Index, AObject) {
  2930. this.CheckIndex(Index);
  2931. this.Changing();
  2932. this.FList[Index].FObject = AObject;
  2933. this.Changed();
  2934. };
  2935. this.SetCapacity = function (NewCapacity) {
  2936. if (NewCapacity < 0) this.Error(rtl.getResStr(pas.RTLConsts,"SListCapacityError"),NewCapacity);
  2937. if (NewCapacity !== this.GetCapacity()) this.FList = rtl.arraySetLength(this.FList,$mod.TStringItem,NewCapacity);
  2938. };
  2939. this.InsertItem = function (Index, S) {
  2940. this.InsertItem$1(Index,S,null);
  2941. };
  2942. this.InsertItem$1 = function (Index, S, O) {
  2943. var It = $mod.TStringItem.$new();
  2944. this.Changing();
  2945. if (this.FCount === this.GetCapacity()) this.Grow();
  2946. It.FString = S;
  2947. It.FObject = O;
  2948. this.FList.splice(Index,0,It);
  2949. this.FCount += 1;
  2950. this.Changed();
  2951. };
  2952. this.DoCompareText = function (s1, s2) {
  2953. var Result = 0;
  2954. if (this.FCaseSensitive) {
  2955. Result = pas.SysUtils.CompareStr(s1,s2)}
  2956. else Result = pas.SysUtils.CompareText(s1,s2);
  2957. return Result;
  2958. };
  2959. this.Destroy = function () {
  2960. this.InternalClear(0,false);
  2961. $mod.TStrings.Destroy.call(this);
  2962. };
  2963. this.Add = function (S) {
  2964. var Result = 0;
  2965. if (!(this.FSortStyle === 2)) {
  2966. Result = this.FCount}
  2967. else if (this.Find(S,{get: function () {
  2968. return Result;
  2969. }, set: function (v) {
  2970. Result = v;
  2971. }})) {
  2972. var $tmp = this.FDuplicates;
  2973. if ($tmp === 0) {
  2974. return Result}
  2975. else if ($tmp === 2) this.Error(rtl.getResStr(pas.RTLConsts,"SDuplicateString"),0);
  2976. };
  2977. this.InsertItem(Result,S);
  2978. return Result;
  2979. };
  2980. this.Clear = function () {
  2981. if (this.FCount === 0) return;
  2982. this.Changing();
  2983. this.InternalClear(0,false);
  2984. this.Changed();
  2985. };
  2986. this.Delete = function (Index) {
  2987. this.CheckIndex(Index);
  2988. this.Changing();
  2989. if (this.FOwnsObjects) pas.SysUtils.FreeAndNil({p: this.FList[Index], get: function () {
  2990. return this.p.FObject;
  2991. }, set: function (v) {
  2992. this.p.FObject = v;
  2993. }});
  2994. this.FList.splice(Index,1);
  2995. this.FList[this.GetCount() - 1].FString = "";
  2996. this.FList[this.GetCount() - 1].FObject = null;
  2997. this.FCount -= 1;
  2998. this.Changed();
  2999. };
  3000. this.Find = function (S, Index) {
  3001. var Result = false;
  3002. var L = 0;
  3003. var R = 0;
  3004. var I = 0;
  3005. var CompareRes = 0;
  3006. Result = false;
  3007. Index.set(-1);
  3008. if (!this.GetSorted()) throw $mod.EListError.$create("Create$1",[rtl.getResStr(pas.RTLConsts,"SErrFindNeedsSortedList")]);
  3009. L = 0;
  3010. R = this.GetCount() - 1;
  3011. while (L <= R) {
  3012. I = L + rtl.trunc((R - L) / 2);
  3013. CompareRes = this.DoCompareText(S,this.FList[I].FString);
  3014. if (CompareRes > 0) {
  3015. L = I + 1}
  3016. else {
  3017. R = I - 1;
  3018. if (CompareRes === 0) {
  3019. Result = true;
  3020. if (this.FDuplicates !== 1) L = I;
  3021. };
  3022. };
  3023. };
  3024. Index.set(L);
  3025. return Result;
  3026. };
  3027. this.IndexOf = function (S) {
  3028. var Result = 0;
  3029. if (!this.GetSorted()) {
  3030. Result = $mod.TStrings.IndexOf.call(this,S)}
  3031. else if (!this.Find(S,{get: function () {
  3032. return Result;
  3033. }, set: function (v) {
  3034. Result = v;
  3035. }})) Result = -1;
  3036. return Result;
  3037. };
  3038. this.Insert = function (Index, S) {
  3039. if (this.FSortStyle === 2) {
  3040. this.Error(rtl.getResStr(pas.RTLConsts,"SSortedListError"),0)}
  3041. else {
  3042. if ((Index < 0) || (Index > this.FCount)) this.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),Index);
  3043. this.InsertItem(Index,S);
  3044. };
  3045. };
  3046. });
  3047. this.TOperation = {"0": "opInsert", opInsert: 0, "1": "opRemove", opRemove: 1};
  3048. this.TComponentStateItem = {"0": "csLoading", csLoading: 0, "1": "csReading", csReading: 1, "2": "csWriting", csWriting: 2, "3": "csDestroying", csDestroying: 3, "4": "csDesigning", csDesigning: 4, "5": "csAncestor", csAncestor: 5, "6": "csUpdating", csUpdating: 6, "7": "csFixups", csFixups: 7, "8": "csFreeNotification", csFreeNotification: 8, "9": "csInline", csInline: 9, "10": "csDesignInstance", csDesignInstance: 10};
  3049. this.TComponentStyleItem = {"0": "csInheritable", csInheritable: 0, "1": "csCheckPropAvail", csCheckPropAvail: 1, "2": "csSubComponent", csSubComponent: 2, "3": "csTransient", csTransient: 3};
  3050. rtl.createClass(this,"TComponent",this.TPersistent,function () {
  3051. this.$init = function () {
  3052. $mod.TPersistent.$init.call(this);
  3053. this.FOwner = null;
  3054. this.FName = "";
  3055. this.FTag = 0;
  3056. this.FComponents = null;
  3057. this.FFreeNotifies = null;
  3058. this.FComponentState = {};
  3059. this.FComponentStyle = {};
  3060. };
  3061. this.$final = function () {
  3062. this.FOwner = undefined;
  3063. this.FComponents = undefined;
  3064. this.FFreeNotifies = undefined;
  3065. this.FComponentState = undefined;
  3066. this.FComponentStyle = undefined;
  3067. $mod.TPersistent.$final.call(this);
  3068. };
  3069. this.Insert = function (AComponent) {
  3070. if (!(this.FComponents != null)) this.FComponents = $mod.TFPList.$create("Create");
  3071. this.FComponents.Add(AComponent);
  3072. AComponent.FOwner = this;
  3073. };
  3074. this.Remove = function (AComponent) {
  3075. AComponent.FOwner = null;
  3076. if (this.FComponents != null) {
  3077. this.FComponents.Remove(AComponent);
  3078. if (this.FComponents.FCount === 0) {
  3079. this.FComponents.$destroy("Destroy");
  3080. this.FComponents = null;
  3081. };
  3082. };
  3083. };
  3084. this.RemoveNotification = function (AComponent) {
  3085. if (this.FFreeNotifies !== null) {
  3086. this.FFreeNotifies.Remove(AComponent);
  3087. if (this.FFreeNotifies.FCount === 0) {
  3088. this.FFreeNotifies.$destroy("Destroy");
  3089. this.FFreeNotifies = null;
  3090. this.FComponentState = rtl.excludeSet(this.FComponentState,8);
  3091. };
  3092. };
  3093. };
  3094. this.SetReference = function (Enable) {
  3095. var aField = null;
  3096. var aValue = null;
  3097. var aOwner = null;
  3098. if (this.FName === "") return;
  3099. if (this.FOwner != null) {
  3100. aOwner = this.FOwner;
  3101. aField = this.FOwner.$class.FieldAddress(this.FName);
  3102. if (aField != null) {
  3103. if (Enable) {
  3104. aValue = this}
  3105. else aValue = null;
  3106. aOwner["" + aField["name"]] = aValue;
  3107. };
  3108. };
  3109. };
  3110. this.ChangeName = function (NewName) {
  3111. this.FName = NewName;
  3112. };
  3113. this.Notification = function (AComponent, Operation) {
  3114. var C = 0;
  3115. if (Operation === 1) this.RemoveFreeNotification(AComponent);
  3116. if (!(this.FComponents != null)) return;
  3117. C = this.FComponents.FCount - 1;
  3118. while (C >= 0) {
  3119. rtl.getObject(this.FComponents.Get(C)).Notification(AComponent,Operation);
  3120. C -= 1;
  3121. if (C >= this.FComponents.FCount) C = this.FComponents.FCount - 1;
  3122. };
  3123. };
  3124. this.SetDesigning = function (Value, SetChildren) {
  3125. var Runner = 0;
  3126. if (Value) {
  3127. this.FComponentState = rtl.includeSet(this.FComponentState,4)}
  3128. else this.FComponentState = rtl.excludeSet(this.FComponentState,4);
  3129. if ((this.FComponents != null) && SetChildren) for (var $l = 0, $end = this.FComponents.FCount - 1; $l <= $end; $l++) {
  3130. Runner = $l;
  3131. rtl.getObject(this.FComponents.Get(Runner)).SetDesigning(Value,true);
  3132. };
  3133. };
  3134. this.SetName = function (NewName) {
  3135. if (this.FName === NewName) return;
  3136. if ((NewName !== "") && !pas.SysUtils.IsValidIdent(NewName,false,false)) throw $mod.EComponentError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SInvalidName"),pas.System.VarRecs(18,NewName)]);
  3137. if (this.FOwner != null) {
  3138. this.FOwner.ValidateRename(this,this.FName,NewName)}
  3139. else this.ValidateRename(null,this.FName,NewName);
  3140. this.SetReference(false);
  3141. this.ChangeName(NewName);
  3142. this.SetReference(true);
  3143. };
  3144. this.ValidateRename = function (AComponent, CurName, NewName) {
  3145. if ((AComponent !== null) && (pas.SysUtils.CompareText(CurName,NewName) !== 0) && (AComponent.FOwner === this) && (this.FindComponent(NewName) !== null)) throw $mod.EComponentError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SDuplicateName"),pas.System.VarRecs(18,NewName)]);
  3146. if ((4 in this.FComponentState) && (this.FOwner !== null)) this.FOwner.ValidateRename(AComponent,CurName,NewName);
  3147. };
  3148. this.ValidateContainer = function (AComponent) {
  3149. AComponent.ValidateInsert(this);
  3150. };
  3151. this.ValidateInsert = function (AComponent) {
  3152. if (AComponent === null) ;
  3153. };
  3154. this.Create$1 = function (AOwner) {
  3155. this.FComponentStyle = rtl.createSet(0);
  3156. if (AOwner != null) AOwner.InsertComponent(this);
  3157. return this;
  3158. };
  3159. this.Destroy = function () {
  3160. var I = 0;
  3161. var C = null;
  3162. this.Destroying();
  3163. if (this.FFreeNotifies != null) {
  3164. I = this.FFreeNotifies.FCount - 1;
  3165. while (I >= 0) {
  3166. C = rtl.getObject(this.FFreeNotifies.Get(I));
  3167. this.FFreeNotifies.Delete(I);
  3168. C.Notification(this,1);
  3169. if (this.FFreeNotifies === null) {
  3170. I = 0}
  3171. else if (I > this.FFreeNotifies.FCount) I = this.FFreeNotifies.FCount;
  3172. I -= 1;
  3173. };
  3174. pas.SysUtils.FreeAndNil({p: this, get: function () {
  3175. return this.p.FFreeNotifies;
  3176. }, set: function (v) {
  3177. this.p.FFreeNotifies = v;
  3178. }});
  3179. };
  3180. this.DestroyComponents();
  3181. if (this.FOwner !== null) this.FOwner.RemoveComponent(this);
  3182. pas.System.TObject.Destroy.call(this);
  3183. };
  3184. this.BeforeDestruction = function () {
  3185. if (!(3 in this.FComponentState)) this.Destroying();
  3186. };
  3187. this.DestroyComponents = function () {
  3188. var acomponent = null;
  3189. while (this.FComponents != null) {
  3190. acomponent = rtl.getObject(this.FComponents.Last());
  3191. this.Remove(acomponent);
  3192. acomponent.$destroy("Destroy");
  3193. };
  3194. };
  3195. this.Destroying = function () {
  3196. var Runner = 0;
  3197. if (3 in this.FComponentState) return;
  3198. this.FComponentState = rtl.includeSet(this.FComponentState,3);
  3199. if (this.FComponents != null) for (var $l = 0, $end = this.FComponents.FCount - 1; $l <= $end; $l++) {
  3200. Runner = $l;
  3201. rtl.getObject(this.FComponents.Get(Runner)).Destroying();
  3202. };
  3203. };
  3204. this.FindComponent = function (AName) {
  3205. var Result = null;
  3206. var I = 0;
  3207. Result = null;
  3208. if ((AName === "") || !(this.FComponents != null)) return Result;
  3209. for (var $l = 0, $end = this.FComponents.FCount - 1; $l <= $end; $l++) {
  3210. I = $l;
  3211. if (pas.SysUtils.CompareText(rtl.getObject(this.FComponents.Get(I)).FName,AName) === 0) {
  3212. Result = rtl.getObject(this.FComponents.Get(I));
  3213. return Result;
  3214. };
  3215. };
  3216. return Result;
  3217. };
  3218. this.RemoveFreeNotification = function (AComponent) {
  3219. this.RemoveNotification(AComponent);
  3220. AComponent.RemoveNotification(this);
  3221. };
  3222. this.InsertComponent = function (AComponent) {
  3223. AComponent.ValidateContainer(this);
  3224. this.ValidateRename(AComponent,"",AComponent.FName);
  3225. if (AComponent.FOwner !== null) AComponent.FOwner.RemoveComponent(AComponent);
  3226. this.Insert(AComponent);
  3227. if (4 in this.FComponentState) AComponent.SetDesigning(true,true);
  3228. this.Notification(AComponent,0);
  3229. };
  3230. this.RemoveComponent = function (AComponent) {
  3231. this.Notification(AComponent,1);
  3232. this.Remove(AComponent);
  3233. AComponent.SetDesigning(false,true);
  3234. this.ValidateRename(AComponent,AComponent.FName,"");
  3235. };
  3236. var $r = this.$rtti;
  3237. $r.addProperty("Name",6,rtl.string,"FName","SetName");
  3238. $r.addProperty("Tag",0,rtl.nativeint,"FTag","FTag",{Default: 0});
  3239. });
  3240. $mod.$implcode = function () {
  3241. $impl.ClassList = null;
  3242. };
  3243. $mod.$init = function () {
  3244. $impl.ClassList = new Object();
  3245. };
  3246. },[]);
  3247. rtl.module("weborworker",["System","JS","Types"],function () {
  3248. "use strict";
  3249. var $mod = this;
  3250. this.isMainBrowserThread = function () {
  3251. return (typeof window !== "undefined");
  3252. };
  3253. this.isWebWorker = function () {
  3254. return (typeof DedicatedWorkerGlobalScope !== 'undefined') &&
  3255. (self instanceof DedicatedWorkerGlobalScope);
  3256. };
  3257. this.IsServiceWorker = function () {
  3258. return (typeof ServiceWorkerGlobalScope !== 'undefined') && (self instanceof ServiceWorkerGlobalScope);
  3259. };
  3260. });
  3261. rtl.module("Rtl.WorkerCommands",["System","SysUtils","JS","weborworker"],function () {
  3262. "use strict";
  3263. var $mod = this;
  3264. this.cmdException = "exception";
  3265. this.channelConsole = "console_output";
  3266. this.cFldCommand = "command";
  3267. rtl.createClass(this,"EWorkerCommand",pas.SysUtils.Exception,function () {
  3268. });
  3269. rtl.createHelper(this,"TCustomWorkerCommandHelper",null,function () {
  3270. this.createCommand = function (aCommand, aSenderID) {
  3271. var Result = null;
  3272. Result = new Object();
  3273. Result.canceled = false;
  3274. Result.command = aCommand;
  3275. Result.senderId = aSenderID;
  3276. return Result;
  3277. };
  3278. });
  3279. rtl.createHelper(this,"TWorkerExceptionCommandHelper",this.TCustomWorkerCommandHelper,function () {
  3280. this.Create = function (aExceptionClass, aExceptionMessage, aThreadID) {
  3281. var Result = null;
  3282. Result = $mod.TCustomWorkerCommandHelper.createCommand($mod.cmdException,pas.SysUtils.IntToStr(aThreadID));
  3283. Result.ExceptionClass = aExceptionClass;
  3284. Result.ExceptionMessage = aExceptionMessage;
  3285. return Result;
  3286. };
  3287. });
  3288. rtl.createClass(this,"TCommandDispatcher",pas.System.TObject,function () {
  3289. rtl.recNewT(this,"TCommandHandlerReg",function () {
  3290. this.SingleHandler = false;
  3291. this.$new = function () {
  3292. var r = Object.create(this);
  3293. r.Handlers = [];
  3294. return r;
  3295. };
  3296. this.$eq = function (b) {
  3297. return (this.Handlers === b.Handlers) && (this.SingleHandler === b.SingleHandler);
  3298. };
  3299. this.$assign = function (s) {
  3300. this.Handlers = rtl.arrayRef(s.Handlers);
  3301. this.SingleHandler = s.SingleHandler;
  3302. return this;
  3303. };
  3304. });
  3305. rtl.recNewT(this,"TJSWorkerReg",function () {
  3306. this.Worker = null;
  3307. this.Name = "";
  3308. this.$eq = function (b) {
  3309. return (this.Worker === b.Worker) && (this.Name === b.Name);
  3310. };
  3311. this.$assign = function (s) {
  3312. this.Worker = s.Worker;
  3313. this.Name = s.Name;
  3314. return this;
  3315. };
  3316. });
  3317. this._Instance = null;
  3318. this._DispatcherClass = null;
  3319. this.$init = function () {
  3320. pas.System.TObject.$init.call(this);
  3321. this.FDefaultSenderID = "";
  3322. this.FMap = null;
  3323. this.FWorkers = [];
  3324. this.FConsoleChannel = null;
  3325. };
  3326. this.$final = function () {
  3327. this.FMap = undefined;
  3328. this.FWorkers = undefined;
  3329. this.FConsoleChannel = undefined;
  3330. pas.System.TObject.$final.call(this);
  3331. };
  3332. this.GetInstance = function () {
  3333. var Result = null;
  3334. var C = null;
  3335. if (!($mod.TCommandDispatcher._Instance != null)) {
  3336. C = $mod.TCommandDispatcher._DispatcherClass;
  3337. if (C === null) C = $mod.TCommandDispatcher;
  3338. $mod.TCommandDispatcher._Instance = C.$create("create$1");
  3339. };
  3340. Result = $mod.TCommandDispatcher._Instance;
  3341. return Result;
  3342. };
  3343. this.IsCommandEvent = function (aEvent) {
  3344. var Result = false;
  3345. var Obj = null;
  3346. Result = (aEvent != null) && rtl.isObject(aEvent.data);
  3347. if (Result) {
  3348. Obj = aEvent.data;
  3349. Result = Obj.hasOwnProperty($mod.cFldCommand) && rtl.isString(Obj[$mod.cFldCommand]);
  3350. };
  3351. return Result;
  3352. };
  3353. this.CheckSenderID = function (aCommand) {
  3354. if (aCommand.senderId === "") aCommand.senderId = this.FDefaultSenderID;
  3355. };
  3356. this.IndexOfWorker = function (aWorker) {
  3357. var Result = 0;
  3358. Result = rtl.length(this.FWorkers) - 1;
  3359. while ((Result >= 0) && (this.FWorkers[Result].Worker !== aWorker)) Result -= 1;
  3360. return Result;
  3361. };
  3362. this.IndexOfWorker$1 = function (aName) {
  3363. var Result = 0;
  3364. Result = rtl.length(this.FWorkers) - 1;
  3365. while ((Result >= 0) && (this.FWorkers[Result].Name !== aName)) Result -= 1;
  3366. return Result;
  3367. };
  3368. this.HandleIncomingMessage = function (aEvent) {
  3369. var lCommand = null;
  3370. if (this.$class.IsCommandEvent(aEvent)) {
  3371. lCommand = aEvent.data;
  3372. lCommand._sender = aEvent.target;
  3373. this.HandleCommand(lCommand);
  3374. };
  3375. };
  3376. this.HandleCommand = function (aCommand) {
  3377. var lCmd = "";
  3378. var lValue = undefined;
  3379. var lHandler = null;
  3380. lCmd = aCommand.command;
  3381. lValue = this.FMap.get(lCmd);
  3382. if (pas.System.Assigned(lValue)) for (var $in = lValue.Handlers, $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  3383. lHandler = $in[$l];
  3384. lHandler(aCommand);
  3385. if (aCommand.canceled) break;
  3386. };
  3387. };
  3388. this.create$1 = function () {
  3389. this.FMap = new Map();
  3390. this.FConsoleChannel = new BroadcastChannel($mod.channelConsole);
  3391. if (pas.weborworker.isMainBrowserThread()) {
  3392. this.FConsoleChannel.addEventListener("message",rtl.createSafeCallback(this,"HandleIncomingMessage"))}
  3393. else self.addEventListener("message",rtl.createSafeCallback(this,"HandleIncomingMessage"));
  3394. return this;
  3395. };
  3396. this.Destroy = function () {
  3397. this.FConsoleChannel.close();
  3398. this.FConsoleChannel = null;
  3399. pas.System.TObject.Destroy.call(this);
  3400. };
  3401. this.SendCommand = function (aWorker, aCommand) {
  3402. this.CheckSenderID(aCommand);
  3403. aWorker.postMessage(aCommand);
  3404. };
  3405. this.SendCommand$2 = function (aCommand) {
  3406. if (!(pas.weborworker.isWebWorker() || pas.weborworker.IsServiceWorker())) throw $mod.EWorkerCommand.$create("Create$1",["Cannot send to starting thread from main page"]);
  3407. this.CheckSenderID(aCommand);
  3408. self.postMessage(aCommand);
  3409. };
  3410. this.RegisterCommandHandler = function (aCommand, aHandler, IsSingle) {
  3411. var lValue = undefined;
  3412. var lNewReg = this.TCommandHandlerReg.$new();
  3413. lValue = this.FMap.get(aCommand);
  3414. if (pas.System.Assigned(lValue)) {
  3415. if (!(lValue.SingleHandler || IsSingle)) {
  3416. lValue.Handlers.push(aHandler)}
  3417. else {
  3418. if (rtl.length(lValue.Handlers) > 0) throw $mod.EWorkerCommand.$create("CreateFmt",["There is already a handler for command %s",pas.System.VarRecs(18,aCommand)]);
  3419. lValue.Handlers = [aHandler];
  3420. lValue.SingleHandler = IsSingle;
  3421. };
  3422. } else {
  3423. lNewReg.$assign(this.TCommandHandlerReg.$new());
  3424. lNewReg.Handlers = [aHandler];
  3425. lNewReg.SingleHandler = IsSingle;
  3426. this.FMap.set(aCommand,this.TCommandHandlerReg.$clone(lNewReg));
  3427. };
  3428. };
  3429. this.RegisterWorker = function (aWorker, aName) {
  3430. var lReg = this.TJSWorkerReg.$new();
  3431. if (this.IndexOfWorker$1(aName) >= 0) throw $mod.EWorkerCommand.$create("CreateFmt",["Duplicate worker name: %s",pas.System.VarRecs(18,aName)]);
  3432. if (this.IndexOfWorker(aWorker) >= 0) throw $mod.EWorkerCommand.$create("Create$1",["Duplicate worker instance"]);
  3433. lReg.Worker = aWorker;
  3434. lReg.Name = aName;
  3435. this.FWorkers = rtl.arrayPush(this.TJSWorkerReg,this.FWorkers,this.TJSWorkerReg.$clone(lReg));
  3436. aWorker.addEventListener("message",rtl.createSafeCallback(this,"HandleIncomingMessage"));
  3437. };
  3438. });
  3439. });
  3440. rtl.module("webassembly",["System","JS"],function () {
  3441. "use strict";
  3442. var $mod = this;
  3443. rtl.recNewT(this,"TJSWebAssemblyMemoryDescriptor",function () {
  3444. this.initial = 0;
  3445. this.maximum = 0;
  3446. this.shared = false;
  3447. this.$eq = function (b) {
  3448. return (this.initial === b.initial) && (this.maximum === b.maximum) && (this.shared === b.shared);
  3449. };
  3450. this.$assign = function (s) {
  3451. this.initial = s.initial;
  3452. this.maximum = s.maximum;
  3453. this.shared = s.shared;
  3454. return this;
  3455. };
  3456. });
  3457. rtl.recNewT(this,"TJSWebAssemblyTableDescriptor",function () {
  3458. this.element = "";
  3459. this.initial = 0;
  3460. this.maximum = 0;
  3461. this.$eq = function (b) {
  3462. return (this.element === b.element) && (this.initial === b.initial) && (this.maximum === b.maximum);
  3463. };
  3464. this.$assign = function (s) {
  3465. this.element = s.element;
  3466. this.initial = s.initial;
  3467. this.maximum = s.maximum;
  3468. return this;
  3469. };
  3470. });
  3471. });
  3472. rtl.module("wasitypes",["System","JS"],function () {
  3473. "use strict";
  3474. var $mod = this;
  3475. this.WASI_ESUCCESS = 0;
  3476. this.WASI_EBADF = 8;
  3477. this.WASI_EINVAL = 28;
  3478. this.WASI_ENOMEM = 48;
  3479. this.WASI_ENOSYS = 52;
  3480. this.WASI_CLOCK_MONOTONIC = 0;
  3481. this.WASI_CLOCK_PROCESS_CPUTIME_ID = 1;
  3482. this.WASI_CLOCK_REALTIME = 2;
  3483. this.WASI_CLOCK_THREAD_CPUTIME_ID = 3;
  3484. this.WASI_EVENTTYPE_CLOCK = 0;
  3485. this.WASI_STDIN_FILENO = 0;
  3486. this.WASI_STDOUT_FILENO = 1;
  3487. this.WASI_STDERR_FILENO = 2;
  3488. this.__WASI_ERRNO_SUCCESS = 0;
  3489. this.__WASI_ERRNO_2BIG = 1;
  3490. this.__WASI_WHENCE_SET = 0;
  3491. this.__WASI_WHENCE_CUR = 1;
  3492. this.__WASI_WHENCE_END = 2;
  3493. this.__WASI_FILETYPE_UNKNOWN = 0;
  3494. this.__WASI_FILETYPE_BLOCK_DEVICE = 1;
  3495. this.__WASI_FILETYPE_CHARACTER_DEVICE = 2;
  3496. this.__WASI_FILETYPE_DIRECTORY = 3;
  3497. this.__WASI_FILETYPE_REGULAR_FILE = 4;
  3498. this.__WASI_FILETYPE_SOCKET_STREAM = 6;
  3499. this.__WASI_FILETYPE_SYMBOLIC_LINK = 7;
  3500. this.__WASI_FSTFLAGS_ATIM = 1;
  3501. this.__WASI_FSTFLAGS_ATIM_NOW = 2;
  3502. this.__WASI_FSTFLAGS_MTIM = 4;
  3503. this.__WASI_FSTFLAGS_MTIM_NOW = 8;
  3504. rtl.recNewT(this,"__wasi_filestat_t",function () {
  3505. this.dev = 0;
  3506. this.ino = 0;
  3507. this.filetype = 0;
  3508. this.nlink = 0;
  3509. this.size = 0;
  3510. this.atim = 0;
  3511. this.mtim = 0;
  3512. this.ctim = 0;
  3513. this.$eq = function (b) {
  3514. return (this.dev === b.dev) && (this.ino === b.ino) && (this.filetype === b.filetype) && (this.nlink === b.nlink) && (this.size === b.size) && (this.atim === b.atim) && (this.mtim === b.mtim) && (this.ctim === b.ctim);
  3515. };
  3516. this.$assign = function (s) {
  3517. this.dev = s.dev;
  3518. this.ino = s.ino;
  3519. this.filetype = s.filetype;
  3520. this.nlink = s.nlink;
  3521. this.size = s.size;
  3522. this.atim = s.atim;
  3523. this.mtim = s.mtim;
  3524. this.ctim = s.ctim;
  3525. return this;
  3526. };
  3527. });
  3528. this.TDirentType = {"0": "dtUnknown", dtUnknown: 0, "1": "dtFile", dtFile: 1, "2": "dtDirectory", dtDirectory: 2, "3": "dtSymlink", dtSymlink: 3, "4": "dtSocket", dtSocket: 4, "5": "dtBlockDevice", dtBlockDevice: 5, "6": "dtCharacterDevice", dtCharacterDevice: 6, "7": "dtFIFO", dtFIFO: 7};
  3529. rtl.recNewT(this,"TWasiFSDirent",function () {
  3530. this.ino = 0;
  3531. this.name = "";
  3532. this.EntryType = 0;
  3533. this.next = 0;
  3534. this.$eq = function (b) {
  3535. return (this.ino === b.ino) && (this.name === b.name) && (this.EntryType === b.EntryType) && (this.next === b.next);
  3536. };
  3537. this.$assign = function (s) {
  3538. this.ino = s.ino;
  3539. this.name = s.name;
  3540. this.EntryType = s.EntryType;
  3541. this.next = s.next;
  3542. return this;
  3543. };
  3544. });
  3545. this.TSeekWhence = {"0": "swBeginning", swBeginning: 0, "1": "swCurrent", swCurrent: 1, "2": "swEnd", swEnd: 2};
  3546. this.TSetTimesFlag = {"0": "stfatime", stfatime: 0, "1": "stfaTimeNow", stfaTimeNow: 1, "2": "stfmTime", stfmTime: 2, "3": "stfmTimeNow", stfmTimeNow: 3};
  3547. rtl.createInterface(this,"IWASIFS","{7DDF5E3C-4C18-30AC-806F-592E720CBE00}",["MkDirAt","RmDirAt","StatAt","StatFD","UTimesAt","UTimes","LinkAt","SymLinkAt","RenameAt","UnLinkAt","OpenAt","ReadLinkAt","Close","Write","Sync","DataSync","Seek","Read","ReadDir","GetPrestat"],null);
  3548. this.DirentMap = [0,4,3,7,6,1,2,0];
  3549. });
  3550. rtl.module("wasienv",["System","SysUtils","Classes","JS","webassembly","Types","wasitypes"],function () {
  3551. "use strict";
  3552. var $mod = this;
  3553. var $impl = $mod.$impl;
  3554. this.SizeInt8 = 1;
  3555. this.SizeInt32 = 4;
  3556. this.SizeInt64 = 8;
  3557. this.SizeUInt8 = 1;
  3558. this.SizeUInt32 = 4;
  3559. this.SizeUInt64 = 8;
  3560. rtl.createClass(this,"EWasmNativeException",pas.SysUtils.Exception,function () {
  3561. this.$init = function () {
  3562. pas.SysUtils.Exception.$init.call(this);
  3563. this.FNativeClass = "";
  3564. this.FNativeMessage = "";
  3565. };
  3566. this.create$2 = function (aNativeClass, aNativeMessage) {
  3567. pas.SysUtils.Exception.CreateFmt.call(this,"Webassembly code raised an exception %s : %s",pas.System.VarRecs(18,aNativeClass,18,aNativeMessage));
  3568. this.FNativeClass = aNativeClass;
  3569. this.FNativeMessage = aNativeMessage;
  3570. return this;
  3571. };
  3572. });
  3573. rtl.createClass(this,"EWasiError",pas.SysUtils.Exception,function () {
  3574. });
  3575. rtl.createClass(this,"EWasiFSError",pas.SysUtils.Exception,function () {
  3576. this.$init = function () {
  3577. pas.SysUtils.Exception.$init.call(this);
  3578. this.FErrorcode = 0;
  3579. };
  3580. });
  3581. rtl.recNewT(this,"TLastExceptionInfo",function () {
  3582. this.ClassName = "";
  3583. this.Message = "";
  3584. this.more = false;
  3585. this.doraise = false;
  3586. this.$eq = function (b) {
  3587. return (this.ClassName === b.ClassName) && (this.Message === b.Message) && (this.more === b.more) && (this.doraise === b.doraise);
  3588. };
  3589. this.$assign = function (s) {
  3590. this.ClassName = s.ClassName;
  3591. this.Message = s.Message;
  3592. this.more = s.more;
  3593. this.doraise = s.doraise;
  3594. return this;
  3595. };
  3596. });
  3597. rtl.createClass(this,"TPas2JSWASIEnvironment",pas.System.TObject,function () {
  3598. this.UTF8TextDecoder = null;
  3599. this.UTF8TextEncoder = null;
  3600. this.IsLittleEndian = true;
  3601. this.$init = function () {
  3602. pas.System.TObject.$init.call(this);
  3603. this.FArguments = null;
  3604. this.FEnvironment = null;
  3605. this.FExitCode = 0;
  3606. this.FImportObject = null;
  3607. this.Finstance = null;
  3608. this.FLogAPI = false;
  3609. this.FModuleInstanceExports = null;
  3610. this.FOnGetConsoleInputBuffer = null;
  3611. this.FOnGetConsoleInputString = null;
  3612. this.FOnStdErrorWrite = null;
  3613. this.FOnStdOutputWrite = null;
  3614. this.FImportExtensions = null;
  3615. this.FWasiFS = null;
  3616. this.FWASIImportName = "";
  3617. this.FMemory = null;
  3618. };
  3619. this.$final = function () {
  3620. this.FArguments = undefined;
  3621. this.FEnvironment = undefined;
  3622. this.FImportObject = undefined;
  3623. this.Finstance = undefined;
  3624. this.FModuleInstanceExports = undefined;
  3625. this.FOnGetConsoleInputBuffer = undefined;
  3626. this.FOnGetConsoleInputString = undefined;
  3627. this.FOnStdErrorWrite = undefined;
  3628. this.FOnStdOutputWrite = undefined;
  3629. this.FImportExtensions = undefined;
  3630. this.FWasiFS = undefined;
  3631. this.FMemory = undefined;
  3632. pas.System.TObject.$final.call(this);
  3633. };
  3634. this.DoRead = function (fd, iovs, iovsLen, atPos, nread) {
  3635. var $Self = this;
  3636. var Result = 0;
  3637. var view = null;
  3638. var avail = 0;
  3639. var bytesRead = 0;
  3640. var ReadBuffer = null;
  3641. var WasiBuffers = [];
  3642. var TotalBufSize = 0;
  3643. function readv(element, index, anArray) {
  3644. var Result = false;
  3645. var b = 0;
  3646. b = 0;
  3647. while ((b < element.byteLength) && (bytesRead < avail)) {
  3648. element[b] = ReadBuffer[bytesRead];
  3649. b += 1;
  3650. bytesRead += 1;
  3651. };
  3652. Result = true;
  3653. return Result;
  3654. };
  3655. TotalBufSize = 0;
  3656. bytesRead = 0;
  3657. view = this.getModuleMemoryDataView();
  3658. WasiBuffers = this.getiovs(view,iovs,iovsLen);
  3659. TotalBufSize = this.GetTotalIOVsLen(rtl.arrayRef(WasiBuffers));
  3660. if (fd === 0) {
  3661. ReadBuffer = this.GetConsoleInputBuffer(TotalBufSize);
  3662. avail = ReadBuffer.byteLength;
  3663. } else if (this.FWasiFS != null) {
  3664. try {
  3665. ReadBuffer = new Uint8Array(new ArrayBuffer(TotalBufSize));
  3666. Result = this.FWasiFS.Read(fd,ReadBuffer,atPos,{get: function () {
  3667. return avail;
  3668. }, set: function (v) {
  3669. avail = v;
  3670. }});
  3671. if (Result !== 0) return Result;
  3672. } catch ($e) {
  3673. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3674. var E = $e;
  3675. Result = this.$class.ErrorToCode(E);
  3676. } else throw $e
  3677. }}
  3678. else {
  3679. ReadBuffer = this.GetFileBuffer(fd,TotalBufSize);
  3680. avail = ReadBuffer.byteLength;
  3681. };
  3682. if (avail > 0) WasiBuffers.forEach(readv);
  3683. view.setUint32(nread,bytesRead,true);
  3684. Result = 0;
  3685. return Result;
  3686. };
  3687. this.GetConsoleInputBuffer = function (aMaxSize) {
  3688. var Result = null;
  3689. var S = "";
  3690. Result = null;
  3691. if (this.FOnGetConsoleInputBuffer != null) {
  3692. this.FOnGetConsoleInputBuffer(this,{get: function () {
  3693. return Result;
  3694. }, set: function (v) {
  3695. Result = v;
  3696. }})}
  3697. else if (this.FOnGetConsoleInputString != null) {
  3698. S = "";
  3699. this.FOnGetConsoleInputString(this,{get: function () {
  3700. return S;
  3701. }, set: function (v) {
  3702. S = v;
  3703. }});
  3704. S = pas.System.Copy(S,1,aMaxSize);
  3705. Result = $impl.toUTF8Array(S);
  3706. } else Result = new Uint8Array(0);
  3707. return Result;
  3708. };
  3709. this.GetFileBuffer = function (FD, aMaxLen) {
  3710. var Result = null;
  3711. Result = new Uint8Array(0);
  3712. return Result;
  3713. };
  3714. this.GetImportObject = function () {
  3715. var Result = null;
  3716. if (!(this.FImportObject != null)) {
  3717. this.FImportObject = new Object();
  3718. this.GetImports(this.FImportObject);
  3719. };
  3720. Result = this.FImportObject;
  3721. return Result;
  3722. };
  3723. this.getiovs = function (view, iovs, iovsLen) {
  3724. var Result = [];
  3725. var I = 0;
  3726. var ArrayBuf = null;
  3727. var Ptr = 0;
  3728. var Buf = 0;
  3729. var BufLen = 0;
  3730. Result = rtl.arraySetLength(Result,null,iovsLen);
  3731. Ptr = iovs;
  3732. for (var $l = 0, $end = iovsLen - 1; $l <= $end; $l++) {
  3733. I = $l;
  3734. Buf = view.getUint32(Ptr,true);
  3735. BufLen = view.getUint32(Ptr + 4,true);
  3736. ArrayBuf = new Uint8Array(this.GetMemory().buffer,Buf,BufLen);
  3737. Result[I] = ArrayBuf;
  3738. Ptr += 8;
  3739. };
  3740. return Result;
  3741. };
  3742. this.GetTotalIOVsLen = function (iovs) {
  3743. var $Self = this;
  3744. var Result = 0;
  3745. var BufLen = 0;
  3746. function calclen(element, index, anArray) {
  3747. var Result = false;
  3748. BufLen = BufLen + element.byteLength;
  3749. Result = true;
  3750. return Result;
  3751. };
  3752. iovs.forEach(calclen);
  3753. Result = BufLen;
  3754. return Result;
  3755. };
  3756. this.GetIOVsAsBytes = function (iovs, iovsLen) {
  3757. var $Self = this;
  3758. var Result = null;
  3759. var view = null;
  3760. var buflen = 0;
  3761. var Written = 0;
  3762. var bufferBytes = null;
  3763. var Buffers = [];
  3764. var Buf = null;
  3765. function writev(element, index, anArray) {
  3766. var Result = false;
  3767. Buf.set(element,Written);
  3768. Written += element.byteLength;
  3769. Result = true;
  3770. return Result;
  3771. };
  3772. view = this.getModuleMemoryDataView();
  3773. Written = 0;
  3774. buflen = 0;
  3775. Buffers = this.getiovs(view,iovs,iovsLen);
  3776. buflen = this.GetTotalIOVsLen(rtl.arrayRef(Buffers));
  3777. bufferBytes = new ArrayBuffer(buflen);
  3778. Buf = new Uint8Array(bufferBytes);
  3779. Buffers.forEach(writev);
  3780. Result = Buf;
  3781. return Result;
  3782. };
  3783. this.GetMemory = function () {
  3784. var Result = null;
  3785. Result = this.FModuleInstanceExports.memory;
  3786. return Result;
  3787. };
  3788. this.SetInstance = function (AValue) {
  3789. if (this.Finstance === AValue) return;
  3790. this.Finstance = AValue;
  3791. this.FModuleInstanceExports = this.Finstance.exports;
  3792. if (!(this.FMemory != null) && (this.FModuleInstanceExports.memory != null)) this.FMemory = this.FModuleInstanceExports.memory;
  3793. };
  3794. this.WriteFileStatToMem = function (BufPtr, Info) {
  3795. var Loc = 0;
  3796. Loc = BufPtr;
  3797. Loc = this.SetMemInfoInt64(Loc,Info.dev);
  3798. Loc = this.SetMemInfoUInt64(Loc,Info.ino);
  3799. Loc = this.SetMemInfoUInt64(Loc,Info.filetype);
  3800. Loc = this.SetMemInfoUInt64(Loc,Info.nlink);
  3801. Loc = this.SetMemInfoUInt64(Loc,Info.size);
  3802. Loc = this.SetMemInfoUInt64(Loc,Info.atim * 1000 * 1000);
  3803. Loc = this.SetMemInfoUInt64(Loc,Info.mtim * 1000 * 1000);
  3804. Loc = this.SetMemInfoUInt64(Loc,Info.ctim * 1000 * 1000);
  3805. };
  3806. this.ErrorToCode = function (E) {
  3807. var Result = 0;
  3808. var EW = null;
  3809. if ($mod.EWasiFSError.isPrototypeOf(E)) {
  3810. Result = EW.FErrorcode}
  3811. else Result = 0;
  3812. if (Result === 0) Result = 52;
  3813. return Result;
  3814. };
  3815. this.DoLog$1 = function (Fmt, Args) {
  3816. pas.System.Writeln(pas.SysUtils.Format(Fmt,Args));
  3817. };
  3818. this.setBigUint64 = function (View, byteOffset, value, littleEndian) {
  3819. var LowWord = 0;
  3820. var HighWord = 0;
  3821. LowWord = value;
  3822. HighWord = Math.floor(value / 4294967296);
  3823. if (littleEndian) {
  3824. View.setUint32(byteOffset + 0,LowWord,littleEndian);
  3825. View.setUint32(byteOffset + 4,HighWord,littleEndian);
  3826. } else {
  3827. View.setUint32(byteOffset + 4,LowWord,littleEndian);
  3828. View.setUint32(byteOffset + 0,HighWord,littleEndian);
  3829. };
  3830. };
  3831. this.setBigInt64 = function (View, byteOffset, value, littleEndian) {
  3832. var LowWord = 0;
  3833. var HighWord = 0;
  3834. LowWord = value;
  3835. HighWord = Math.floor(value / 4294967296);
  3836. if (littleEndian) {
  3837. View.setInt32(byteOffset + 0,LowWord,littleEndian);
  3838. View.setInt32(byteOffset + 4,HighWord,littleEndian);
  3839. } else {
  3840. View.setInt32(byteOffset + 4,LowWord,littleEndian);
  3841. View.setInt32(byteOffset + 0,HighWord,littleEndian);
  3842. };
  3843. };
  3844. this.DoConsoleWrite = function (IsStdErr, aBytes) {
  3845. var $Self = this;
  3846. function TryConvert() {
  3847. var Result = "";
  3848. Result = "";
  3849. Result=String.fromCharCode.apply(null, aBytes);
  3850. return Result;
  3851. };
  3852. var S = "";
  3853. var Evt = null;
  3854. try {
  3855. S = this.GetUTF8StringFromArray(aBytes);
  3856. } catch ($e) {
  3857. S = TryConvert();
  3858. };
  3859. if (IsStdErr) {
  3860. Evt = this.FOnStdErrorWrite}
  3861. else Evt = this.FOnStdOutputWrite;
  3862. if (Evt != null) Evt($Self,S);
  3863. };
  3864. this.GetImports = function (aImports) {
  3865. aImports["args_get"] = rtl.createCallback(this,"args_get");
  3866. aImports["args_sizes_get"] = rtl.createCallback(this,"args_sizes_get");
  3867. aImports["clock_res_get"] = rtl.createCallback(this,"clock_res_get");
  3868. aImports["clock_time_get"] = rtl.createCallback(this,"clock_time_get");
  3869. aImports["environ_get"] = rtl.createCallback(this,"environ_get");
  3870. aImports["environ_sizes_get"] = rtl.createCallback(this,"environ_sizes_get");
  3871. aImports["fd_advise"] = rtl.createCallback(this,"fd_advise");
  3872. aImports["fd_allocate"] = rtl.createCallback(this,"fd_allocate");
  3873. aImports["fd_close"] = rtl.createCallback(this,"fd_close");
  3874. aImports["fd_datasync"] = rtl.createCallback(this,"fd_datasync");
  3875. aImports["fd_fdstat_get"] = rtl.createCallback(this,"fd_fdstat_get");
  3876. aImports["fd_fdstat_set_flags"] = rtl.createCallback(this,"fd_fdstat_set_flags");
  3877. aImports["fd_fdstat_set_rights"] = rtl.createCallback(this,"fd_fdstat_set_rights");
  3878. aImports["fd_filestat_get"] = rtl.createCallback(this,"fd_filestat_get");
  3879. aImports["fd_filestat_set_size"] = rtl.createCallback(this,"fd_filestat_set_size");
  3880. aImports["fd_filestat_set_times"] = rtl.createCallback(this,"fd_filestat_set_times");
  3881. aImports["fd_pread"] = rtl.createCallback(this,"fd_pread");
  3882. aImports["fd_prestat_dir_name"] = rtl.createCallback(this,"fd_prestat_dir_name");
  3883. aImports["fd_prestat_get"] = rtl.createCallback(this,"fd_prestat_get");
  3884. aImports["fd_pwrite"] = rtl.createCallback(this,"fd_pwrite");
  3885. aImports["fd_read"] = rtl.createCallback(this,"fd_read");
  3886. aImports["fd_readdir"] = rtl.createCallback(this,"fd_readdir");
  3887. aImports["fd_renumber"] = rtl.createCallback(this,"fd_renumber");
  3888. aImports["fd_seek"] = rtl.createCallback(this,"fd_seek");
  3889. aImports["fd_sync"] = rtl.createCallback(this,"fd_sync");
  3890. aImports["fd_tell"] = rtl.createCallback(this,"fd_tell");
  3891. aImports["fd_write"] = rtl.createCallback(this,"fd_write");
  3892. aImports["path_create_directory"] = rtl.createCallback(this,"path_create_directory");
  3893. aImports["path_filestat_get"] = rtl.createCallback(this,"path_filestat_get");
  3894. aImports["path_filestat_set_times"] = rtl.createCallback(this,"path_filestat_set_times");
  3895. aImports["path_link"] = rtl.createCallback(this,"path_link");
  3896. aImports["path_open"] = rtl.createCallback(this,"path_open");
  3897. aImports["path_readlink"] = rtl.createCallback(this,"path_readlink");
  3898. aImports["path_remove_directory"] = rtl.createCallback(this,"path_remove_directory");
  3899. aImports["path_rename"] = rtl.createCallback(this,"path_rename");
  3900. aImports["path_symlink"] = rtl.createCallback(this,"path_symlink");
  3901. aImports["path_unlink_file"] = rtl.createCallback(this,"path_unlink_file");
  3902. aImports["poll_oneoff"] = rtl.createCallback(this,"poll_oneoff");
  3903. aImports["proc_exit"] = rtl.createCallback(this,"proc_exit");
  3904. aImports["proc_raise"] = rtl.createCallback(this,"proc_raise");
  3905. aImports["random_get"] = rtl.createCallback(this,"random_get");
  3906. aImports["sched_yield"] = rtl.createCallback(this,"sched_yield");
  3907. aImports["sock_recv"] = rtl.createCallback(this,"sock_recv");
  3908. aImports["sock_send"] = rtl.createCallback(this,"sock_send");
  3909. aImports["sock_shutdown"] = rtl.createCallback(this,"sock_shutdown");
  3910. };
  3911. this.GetTime = function (aClockID) {
  3912. var Result = 0;
  3913. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.GetTime(%d)",pas.System.VarRecs(19,aClockID));
  3914. Result = -1;
  3915. var $tmp = aClockID;
  3916. if ($tmp === 0) {
  3917. Result = Date.now()}
  3918. else if ($tmp === 2) {
  3919. Result = Date.now()}
  3920. else if (($tmp === 1) || ($tmp === 3)) Result = Date.now();
  3921. Result = Result * 1000000;
  3922. return Result;
  3923. };
  3924. this.getModuleMemoryDataView = function () {
  3925. var Result = null;
  3926. Result = new DataView(this.GetMemory().buffer);
  3927. return Result;
  3928. };
  3929. this.AddExtension = function (aExtension) {
  3930. if (!(this.FImportExtensions != null)) this.FImportExtensions = pas.Classes.TFPList.$create("Create");
  3931. this.FImportExtensions.Add(aExtension);
  3932. };
  3933. this.RemoveExtension = function (aExtension) {
  3934. if (this.FImportExtensions != null) this.FImportExtensions.Remove(aExtension);
  3935. };
  3936. this.args_get = function (argv, argvBuf) {
  3937. var Result = 0;
  3938. var Ptr = 0;
  3939. var PtrV = 0;
  3940. var S = "";
  3941. var i = 0;
  3942. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.args_get([%x],[%x])",pas.System.VarRecs(0,argv,0,argvBuf));
  3943. Ptr = argvBuf;
  3944. PtrV = argv;
  3945. for (var $l = 0, $end = this.FArguments.GetCount() - 1; $l <= $end; $l++) {
  3946. i = $l;
  3947. S = this.FArguments.Get(i);
  3948. PtrV = this.SetMemInfoUInt32(PtrV,Ptr);
  3949. Ptr = Ptr + this.SetUTF8StringInMem(Ptr,S.length,S);
  3950. Ptr = this.SetMemInfoUInt8(Ptr,0);
  3951. };
  3952. Result = 0;
  3953. return Result;
  3954. };
  3955. this.args_sizes_get = function (argc, argvBufSize) {
  3956. var Result = 0;
  3957. var View = null;
  3958. var Size = 0;
  3959. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.args_sizes_get([%x],[%x])",pas.System.VarRecs(0,argc,0,argvBufSize));
  3960. View = this.getModuleMemoryDataView();
  3961. View.setUint32(argc,this.FArguments.GetCount(),true);
  3962. Size = 0;
  3963. if (this.FArguments.GetCount() > 0) Size = this.FArguments.GetTextStr().length + 1;
  3964. View.setUint32(argvBufSize,Size,true);
  3965. Result = 0;
  3966. return Result;
  3967. };
  3968. this.clock_res_get = function (clockId, resolution) {
  3969. var Result = 0;
  3970. var view = null;
  3971. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.clock_res_get(%d,%d)",pas.System.VarRecs(19,clockId,19,resolution));
  3972. view = this.getModuleMemoryDataView();
  3973. this.$class.setBigUint64(view,resolution,0,true);
  3974. Result = 0;
  3975. return Result;
  3976. };
  3977. this.clock_time_get = function (clockId, precision, time) {
  3978. var Result = 0;
  3979. var view = null;
  3980. var n = 0;
  3981. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.clock_time_get(%d,%d,[%x])",pas.System.VarRecs(19,clockId,19,precision,0,time));
  3982. view = this.getModuleMemoryDataView();
  3983. n = this.GetTime(clockId);
  3984. if (n === -1) {
  3985. Result = 28}
  3986. else {
  3987. this.$class.setBigUint64(view,time,n,true);
  3988. Result = 0;
  3989. };
  3990. return Result;
  3991. };
  3992. this.environ_get = function (environ, environBuf) {
  3993. var Result = 0;
  3994. var S = "";
  3995. var I = 0;
  3996. var PtrV = 0;
  3997. var Ptr = 0;
  3998. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.environ_get([%x],[%x])",pas.System.VarRecs(0,environ,0,environBuf));
  3999. Ptr = environBuf;
  4000. PtrV = environ;
  4001. for (var $l = 0, $end = this.FEnvironment.GetCount() - 1; $l <= $end; $l++) {
  4002. I = $l;
  4003. S = this.FEnvironment.Get(I);
  4004. PtrV = this.SetMemInfoUInt32(PtrV,Ptr);
  4005. Ptr = Ptr + this.SetUTF8StringInMem(Ptr,S.length,S);
  4006. Ptr = this.SetMemInfoUInt8(Ptr,0);
  4007. };
  4008. Result = 0;
  4009. return Result;
  4010. };
  4011. this.environ_sizes_get = function (environCount, environBufSize) {
  4012. var Result = 0;
  4013. var View = null;
  4014. var Size = 0;
  4015. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.environ_sizes_get([%x],[%x])",pas.System.VarRecs(0,environCount,0,environBufSize));
  4016. View = this.getModuleMemoryDataView();
  4017. View.setUint32(environCount,this.FEnvironment.GetCount(),true);
  4018. Size = 0;
  4019. if (this.FEnvironment.GetCount() > 0) Size = this.FEnvironment.GetTextStr().length + 1;
  4020. View.setUint32(environBufSize,Size,true);
  4021. Result = 0;
  4022. return Result;
  4023. };
  4024. this.fd_advise = function (fd, offset, len, advice) {
  4025. var Result = 0;
  4026. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_advise(%d,%d,%d,%d)",pas.System.VarRecs(19,fd,19,offset,19,len,19,advice));
  4027. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_advise");
  4028. Result = 52;
  4029. return Result;
  4030. };
  4031. this.fd_allocate = function (fd, offset, len) {
  4032. var Result = 0;
  4033. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_allocate(%d,%d,%d)",pas.System.VarRecs(19,fd,19,offset,19,len));
  4034. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_allocate");
  4035. Result = 52;
  4036. return Result;
  4037. };
  4038. this.fd_close = function (fd) {
  4039. var Result = 0;
  4040. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_close(%d)",pas.System.VarRecs(19,fd));
  4041. if (!(this.FWasiFS != null)) {
  4042. Result = 52}
  4043. else try {
  4044. Result = this.FWasiFS.Close(fd);
  4045. } catch ($e) {
  4046. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4047. var E = $e;
  4048. Result = this.$class.ErrorToCode(E);
  4049. } else throw $e
  4050. };
  4051. return Result;
  4052. };
  4053. this.fd_datasync = function (fd) {
  4054. var Result = 0;
  4055. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_datasync(%d)",pas.System.VarRecs(19,fd));
  4056. if (!(this.FWasiFS != null)) {
  4057. Result = 52}
  4058. else try {
  4059. Result = this.FWasiFS.DataSync(fd);
  4060. } catch ($e) {
  4061. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4062. var E = $e;
  4063. Result = this.$class.ErrorToCode(E);
  4064. } else throw $e
  4065. };
  4066. return Result;
  4067. };
  4068. this.fd_fdstat_get = function (fd, bufPtr) {
  4069. var Result = 0;
  4070. var View = null;
  4071. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_fdstat_get(%d,%d)",pas.System.VarRecs(19,fd,0,bufPtr));
  4072. View = this.getModuleMemoryDataView();
  4073. View.setUint8(bufPtr,fd);
  4074. View.setUint16(bufPtr + 2,0,true);
  4075. View.setUint16(bufPtr + 4,0,true);
  4076. this.$class.setBigUint64(View,bufPtr + 8,0,true);
  4077. this.$class.setBigUint64(View,bufPtr + 8 + 8,0,true);
  4078. Result = 0;
  4079. return Result;
  4080. };
  4081. this.fd_fdstat_set_flags = function (fd, flags) {
  4082. var Result = 0;
  4083. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_fdstat_set_flags(%d,%d)",pas.System.VarRecs(19,fd,19,flags));
  4084. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_fdstat_set_flags");
  4085. Result = 52;
  4086. return Result;
  4087. };
  4088. this.fd_fdstat_set_rights = function (fd, fsRightsBase, fsRightsInheriting) {
  4089. var Result = 0;
  4090. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_fdstat_set_rights(%d,%d,%d)",pas.System.VarRecs(19,fd,19,fsRightsBase,19,fsRightsInheriting));
  4091. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_fdstat_set_rights");
  4092. Result = 52;
  4093. return Result;
  4094. };
  4095. this.fd_filestat_get = function (fd, bufPtr) {
  4096. var Result = 0;
  4097. var Info = pas.wasitypes.__wasi_filestat_t.$new();
  4098. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_filestat_get(%d,[%x])",pas.System.VarRecs(19,fd,0,bufPtr));
  4099. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_filestat_get");
  4100. if (!(this.FWasiFS != null)) {
  4101. Result = 52}
  4102. else try {
  4103. Result = this.FWasiFS.StatFD(fd,Info);
  4104. if (Result === 0) this.WriteFileStatToMem(bufPtr,pas.wasitypes.__wasi_filestat_t.$clone(Info));
  4105. } catch ($e) {
  4106. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4107. var E = $e;
  4108. Result = this.$class.ErrorToCode(E);
  4109. } else throw $e
  4110. };
  4111. return Result;
  4112. };
  4113. this.fd_filestat_set_size = function (fd, stSize) {
  4114. var Result = 0;
  4115. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_filestat_set_size(%d,%d)",pas.System.VarRecs(19,fd,19,stSize));
  4116. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_filestat_set_size");
  4117. Result = 52;
  4118. return Result;
  4119. };
  4120. this.fd_filestat_set_times = function (fd, stAtim, stMtim, fstflags) {
  4121. var $Self = this;
  4122. var Result = 0;
  4123. var Flags = {};
  4124. function MaybeFlag(src, Flag) {
  4125. if ((fstflags & src) === src) Flags = rtl.includeSet(Flags,Flag);
  4126. };
  4127. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_filestat_set_times(%d,%d,%d)",pas.System.VarRecs(19,fd,19,stAtim,19,stMtim,19,fstflags));
  4128. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_filestat_set_times");
  4129. if (!(this.FWasiFS != null)) {
  4130. Result = 52}
  4131. else try {
  4132. MaybeFlag(1,0);
  4133. MaybeFlag(2,1);
  4134. MaybeFlag(4,2);
  4135. MaybeFlag(8,3);
  4136. Result = this.FWasiFS.UTimes(fd,new Date(stAtim),new Date(stMtim),rtl.refSet(Flags));
  4137. } catch ($e) {
  4138. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4139. var E = $e;
  4140. Result = this.$class.ErrorToCode(E);
  4141. } else throw $e
  4142. };
  4143. return Result;
  4144. };
  4145. this.fd_pread = function (fd, iovs, iovsLen, offset, nread) {
  4146. var Result = 0;
  4147. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_pread(%d,[%x],%d,%d,[%x])",pas.System.VarRecs(19,fd,0,iovs,19,iovsLen,19,offset,0,nread));
  4148. Result = this.DoRead(fd,iovs,iovsLen,offset,nread);
  4149. return Result;
  4150. };
  4151. this.fd_prestat_dir_name = function (fd, pathPtr, pathLen) {
  4152. var Result = 0;
  4153. var S = "";
  4154. var Len = 0;
  4155. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_prestat_dir_name(%d,[%d],%d)",pas.System.VarRecs(19,fd,0,pathPtr,19,pathLen));
  4156. if (this.FWasiFS != null) {
  4157. S = this.FWasiFS.GetPrestat(fd);
  4158. if (S !== "") {
  4159. Len = S.length;
  4160. if (Len > pathLen) Len = pathLen;
  4161. this.SetUTF8StringInMem(pathPtr,Len,S);
  4162. Result = 0;
  4163. } else Result = 8;
  4164. } else {
  4165. if (fd === 3) {
  4166. this.SetUTF8StringInMem(pathPtr,1,"/");
  4167. Result = 0;
  4168. } else Result = 8;
  4169. };
  4170. return Result;
  4171. };
  4172. this.fd_prestat_get = function (fd, bufPtr) {
  4173. var Result = 0;
  4174. var S = "";
  4175. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_prestat_get(%d,[%d])",pas.System.VarRecs(19,fd,0,bufPtr));
  4176. if (this.FWasiFS != null) {
  4177. S = this.FWasiFS.GetPrestat(fd);
  4178. if (S !== "") {
  4179. this.SetMemInfoInt32(bufPtr,0);
  4180. this.SetMemInfoInt32(bufPtr + 4,S.length);
  4181. Result = 0;
  4182. } else Result = 8;
  4183. } else {
  4184. if (fd === 3) {
  4185. this.SetMemInfoInt32(bufPtr,0);
  4186. this.SetMemInfoInt32(bufPtr + 4,1);
  4187. Result = 0;
  4188. };
  4189. Result = 8;
  4190. };
  4191. return Result;
  4192. };
  4193. this.fd_pwrite = function (fd, iovs, iovsLen, offset, nwritten) {
  4194. var Result = 0;
  4195. var view = null;
  4196. var Buf = null;
  4197. var written = 0;
  4198. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_prite(%d,[%d],%d,%d,[%d])",pas.System.VarRecs(19,fd,19,iovs,19,iovsLen,19,offset,19,nwritten));
  4199. if ((fd === 1) || (fd === 2)) {
  4200. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  4201. written = Buf.byteLength;
  4202. this.DoConsoleWrite(fd === 2,Buf);
  4203. view.setUint32(nwritten,written,true);
  4204. Result = 0;
  4205. } else if (!(this.FWasiFS != null)) {
  4206. Result = 52}
  4207. else {
  4208. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  4209. Result = this.FWasiFS.Write(fd,Buf,-1,{get: function () {
  4210. return written;
  4211. }, set: function (v) {
  4212. written = v;
  4213. }});
  4214. if (Result === 0) view.setUint32(nwritten,written,true);
  4215. };
  4216. Result = 52;
  4217. return Result;
  4218. };
  4219. this.fd_read = function (fd, iovs, iovsLen, nread) {
  4220. var Result = 0;
  4221. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_read(%d,[%x],%d,[%x])",pas.System.VarRecs(19,fd,0,iovs,19,iovsLen,0,nread));
  4222. Result = this.DoRead(fd,iovs,iovsLen,-1,nread);
  4223. return Result;
  4224. };
  4225. this.fd_readdir = function (fd, bufPtr, bufLen, cookie, bufusedPtr) {
  4226. var Result = 0;
  4227. var Dirent = pas.wasitypes.TWasiFSDirent.$new();
  4228. var NameArray = null;
  4229. var NameLen = 0;
  4230. var Ptr = 0;
  4231. var Res = 0;
  4232. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_readdir(%d,[%x],%d,%d,[%x])",pas.System.VarRecs(19,fd,0,bufPtr,19,bufLen,19,cookie,0,bufusedPtr));
  4233. if (!(this.FWasiFS != null)) {
  4234. Result = 52}
  4235. else try {
  4236. Res = this.FWasiFS.ReadDir(fd,pas.JS.AsIntNumber(cookie),Dirent);
  4237. Result = 0;
  4238. Ptr = bufPtr;
  4239. while (((Ptr - bufPtr) < bufLen) && (Res === 0)) {
  4240. NameArray = this.UTF8TextEncoder.encode(Dirent.name);
  4241. NameLen = NameArray.byteLength;
  4242. Ptr = this.SetMemInfoUInt64(Ptr,Dirent.next);
  4243. Ptr = this.SetMemInfoUInt64(Ptr,Dirent.ino);
  4244. Ptr = this.SetMemInfoInt32(Ptr,NameLen);
  4245. Ptr = this.SetMemInfoInt32(Ptr,pas.wasitypes.DirentMap[Dirent.EntryType]);
  4246. if (this.SetUTF8StringInMem(Ptr,bufLen - 18,Dirent.name) !== -1) {
  4247. Ptr = Ptr + NameLen;
  4248. cookie = Dirent.next;
  4249. Res = this.FWasiFS.ReadDir(fd,pas.JS.AsIntNumber(cookie),Dirent);
  4250. } else Res = 48;
  4251. };
  4252. this.SetMemInfoInt32(bufusedPtr,Ptr - bufPtr);
  4253. } catch ($e) {
  4254. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4255. var E = $e;
  4256. Result = this.$class.ErrorToCode(E);
  4257. } else throw $e
  4258. };
  4259. return Result;
  4260. };
  4261. this.fd_renumber = function (afrom, ato) {
  4262. var Result = 0;
  4263. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_renumber(%d,%d)",pas.System.VarRecs(19,afrom,19,ato));
  4264. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_renumber");
  4265. Result = 52;
  4266. return Result;
  4267. };
  4268. this.fd_seek = function (fd, offset, whence, newOffsetPtr) {
  4269. var Result = 0;
  4270. var lWhence = 0;
  4271. var NewPos = 0;
  4272. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_seek(%d,%d,%d,[%x])",pas.System.VarRecs(19,fd,19,offset,19,whence,0,newOffsetPtr));
  4273. if (!(this.FWasiFS != null)) {
  4274. Result = 52}
  4275. else try {
  4276. lWhence = 0;
  4277. var $tmp = whence;
  4278. if ($tmp === 1) {
  4279. lWhence = 1}
  4280. else if ($tmp === 2) {
  4281. lWhence = 2}
  4282. else if ($tmp === 0) {
  4283. lWhence = 0}
  4284. else {
  4285. Result = 28;
  4286. };
  4287. Result = this.FWasiFS.Seek(fd,offset,lWhence,{get: function () {
  4288. return NewPos;
  4289. }, set: function (v) {
  4290. NewPos = v;
  4291. }});
  4292. if (Result === 0) this.SetMemInfoInt64(newOffsetPtr,NewPos);
  4293. } catch ($e) {
  4294. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4295. var E = $e;
  4296. Result = this.$class.ErrorToCode(E);
  4297. } else throw $e
  4298. };
  4299. return Result;
  4300. };
  4301. this.fd_sync = function (fd) {
  4302. var Result = 0;
  4303. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_sync(%d)",pas.System.VarRecs(19,fd));
  4304. if (!(this.FWasiFS != null)) {
  4305. Result = 52}
  4306. else try {
  4307. Result = this.FWasiFS.Sync(fd);
  4308. } catch ($e) {
  4309. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4310. var E = $e;
  4311. Result = this.$class.ErrorToCode(E);
  4312. } else throw $e
  4313. };
  4314. return Result;
  4315. };
  4316. this.fd_tell = function (fd, offsetPtr) {
  4317. var Result = 0;
  4318. var NewPos = 0;
  4319. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_tell(%d,[%x])",pas.System.VarRecs(19,fd,0,offsetPtr));
  4320. if (!(this.FWasiFS != null)) {
  4321. Result = 52}
  4322. else try {
  4323. Result = this.FWasiFS.Seek(fd,0,1,{get: function () {
  4324. return NewPos;
  4325. }, set: function (v) {
  4326. NewPos = v;
  4327. }});
  4328. if (Result === 0) this.SetMemInfoInt32(offsetPtr,NewPos);
  4329. } catch ($e) {
  4330. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4331. var E = $e;
  4332. Result = this.$class.ErrorToCode(E);
  4333. } else throw $e
  4334. };
  4335. return Result;
  4336. };
  4337. this.fd_write = function (fd, iovs, iovsLen, nwritten) {
  4338. var Result = 0;
  4339. var view = null;
  4340. var Buf = null;
  4341. var written = 0;
  4342. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_write(%d,[%d],%d,[%d])",pas.System.VarRecs(19,fd,19,iovs,19,iovsLen,19,nwritten));
  4343. view = this.getModuleMemoryDataView();
  4344. if ((fd === 1) || (fd === 2)) {
  4345. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  4346. written = Buf.byteLength;
  4347. this.DoConsoleWrite(fd === 2,Buf);
  4348. view.setUint32(nwritten,written,true);
  4349. Result = 0;
  4350. } else if (!(this.FWasiFS != null)) {
  4351. Result = 52}
  4352. else {
  4353. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  4354. Result = this.FWasiFS.Write(fd,Buf,-1,{get: function () {
  4355. return written;
  4356. }, set: function (v) {
  4357. written = v;
  4358. }});
  4359. if (Result === 0) view.setUint32(nwritten,written,true);
  4360. };
  4361. return Result;
  4362. };
  4363. this.path_create_directory = function (fd, pathPtr, pathLen) {
  4364. var Result = 0;
  4365. var S = "";
  4366. S = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4367. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_create_directory(%d,'%s')",pas.System.VarRecs(19,fd,18,S));
  4368. if (!(this.FWasiFS != null)) {
  4369. Result = 52}
  4370. else try {
  4371. Result = this.FWasiFS.MkDirAt(fd,S);
  4372. } catch ($e) {
  4373. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4374. var E = $e;
  4375. Result = this.$class.ErrorToCode(E);
  4376. } else throw $e
  4377. };
  4378. return Result;
  4379. };
  4380. this.path_filestat_get = function (fd, flags, pathPtr, pathLen, bufPtr) {
  4381. var Result = 0;
  4382. var aPath = "";
  4383. var Info = pas.wasitypes.__wasi_filestat_t.$new();
  4384. aPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4385. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_filestat_get(%d,%d,'%s',[%x])",pas.System.VarRecs(19,fd,19,flags,18,aPath,0,bufPtr));
  4386. if (!(this.FWasiFS != null)) {
  4387. Result = 52}
  4388. else try {
  4389. Result = this.FWasiFS.StatAt(fd,aPath,Info);
  4390. if (Result === 0) this.WriteFileStatToMem(bufPtr,pas.wasitypes.__wasi_filestat_t.$clone(Info));
  4391. } catch ($e) {
  4392. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4393. var E = $e;
  4394. Result = this.$class.ErrorToCode(E);
  4395. } else throw $e
  4396. };
  4397. return Result;
  4398. };
  4399. this.path_filestat_set_times = function (fd, fstflags, pathPtr, pathLen, stAtim, stMtim) {
  4400. var Result = 0;
  4401. var aPath = "";
  4402. aPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4403. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_filestat_set_times(%d,%d,'%s',%d,%d)",pas.System.VarRecs(19,fd,19,fstflags,18,aPath,19,stAtim,19,stMtim));
  4404. if (!(this.FWasiFS != null)) {
  4405. Result = 52}
  4406. else try {
  4407. Result = this.FWasiFS.UTimesAt(fd,aPath,new Date(stAtim),new Date(stMtim),false);
  4408. } catch ($e) {
  4409. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4410. var E = $e;
  4411. Result = this.$class.ErrorToCode(E);
  4412. } else throw $e
  4413. };
  4414. return Result;
  4415. };
  4416. this.path_link = function (oldFd, oldFlags, oldPath, oldPathLen, newFd, NewPath, newPathLen) {
  4417. var Result = 0;
  4418. var lOld = "";
  4419. var lNew = "";
  4420. lOld = this.GetUTF8StringFromMem(oldPath,oldPathLen);
  4421. lNew = this.GetUTF8StringFromMem(NewPath,newPathLen);
  4422. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_link(%d,%d,'%s',%d,'%s')",pas.System.VarRecs(19,oldFd,19,oldFlags,18,lOld,19,newFd,18,lNew));
  4423. if (!(this.FWasiFS != null)) {
  4424. Result = 52}
  4425. else try {
  4426. Result = this.FWasiFS.LinkAt(oldFd,lOld,newFd,lNew);
  4427. } catch ($e) {
  4428. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4429. var E = $e;
  4430. Result = this.$class.ErrorToCode(E);
  4431. } else throw $e
  4432. };
  4433. return Result;
  4434. };
  4435. this.path_open = function (dirfd, dirflags, pathPtr, pathLen, oflags, fsRightsBase, fsRightsInheriting, fsFlags, fd) {
  4436. var Result = 0;
  4437. var lPath = "";
  4438. var lFD = 0;
  4439. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4440. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_open(%d,%d,'%s',%d,%d,%d,%d,[%x])",pas.System.VarRecs(19,dirfd,19,dirflags,18,lPath,19,oflags,19,fsRightsBase,19,fsRightsInheriting,19,fsFlags,0,fd));
  4441. if (!(this.FWasiFS != null)) {
  4442. Result = 52}
  4443. else try {
  4444. Result = this.FWasiFS.OpenAt(dirfd,dirflags,lPath,oflags,fsRightsBase,fsRightsInheriting,fsFlags,{get: function () {
  4445. return lFD;
  4446. }, set: function (v) {
  4447. lFD = v;
  4448. }});
  4449. if (Result === 0) this.SetMemInfoInt32(fd,lFD);
  4450. } catch ($e) {
  4451. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4452. var E = $e;
  4453. Result = this.$class.ErrorToCode(E);
  4454. } else throw $e
  4455. };
  4456. return Result;
  4457. };
  4458. this.path_readlink = function (fd, pathPtr, pathLen, buf, bufLen, bufused) {
  4459. var Result = 0;
  4460. var lTarget = "";
  4461. var lPath = "";
  4462. var Written = 0;
  4463. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4464. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_readlink(%d,'%s',[%x],%d,%d,[%x])",pas.System.VarRecs(19,fd,18,lPath,0,buf,19,bufLen,0,bufused));
  4465. console.log("Unimplemented: TPas2JSWASIEnvironment.path_readlink");
  4466. if (!(this.FWasiFS != null)) {
  4467. Result = 52}
  4468. else try {
  4469. Result = this.FWasiFS.ReadLinkAt(fd,lPath,{get: function () {
  4470. return lTarget;
  4471. }, set: function (v) {
  4472. lTarget = v;
  4473. }});
  4474. if (Result === 0) {
  4475. Written = this.SetUTF8StringInMem(buf,bufLen,lTarget);
  4476. if (Written === -1) {
  4477. Result = 1}
  4478. else this.SetMemInfoInt32(bufused,Written);
  4479. };
  4480. } catch ($e) {
  4481. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4482. var E = $e;
  4483. Result = this.$class.ErrorToCode(E);
  4484. } else throw $e
  4485. };
  4486. Result = 52;
  4487. return Result;
  4488. };
  4489. this.path_remove_directory = function (fd, pathPtr, pathLen) {
  4490. var Result = 0;
  4491. var lPath = "";
  4492. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4493. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_remove_directory(%d,'%s')",pas.System.VarRecs(19,fd,18,lPath));
  4494. if (!(this.FWasiFS != null)) {
  4495. Result = 52}
  4496. else try {
  4497. Result = this.FWasiFS.RmDirAt(fd,lPath);
  4498. } catch ($e) {
  4499. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4500. var E = $e;
  4501. Result = this.$class.ErrorToCode(E);
  4502. } else throw $e
  4503. };
  4504. return Result;
  4505. };
  4506. this.path_rename = function (oldFd, oldPath, oldPathLen, newFd, newPath, newPathLen) {
  4507. var Result = 0;
  4508. var lOld = "";
  4509. var lNew = "";
  4510. lOld = this.GetUTF8StringFromMem(oldPath,oldPathLen);
  4511. lNew = this.GetUTF8StringFromMem(newPath,newPathLen);
  4512. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_rename(%d,'%s',%d,'%s')",pas.System.VarRecs(19,oldFd,18,lOld,19,newFd,18,lNew));
  4513. if (!(this.FWasiFS != null)) {
  4514. Result = 52}
  4515. else try {
  4516. Result = this.FWasiFS.RenameAt(oldFd,lOld,newFd,lNew);
  4517. } catch ($e) {
  4518. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4519. var E = $e;
  4520. Result = this.$class.ErrorToCode(E);
  4521. } else throw $e
  4522. };
  4523. return Result;
  4524. };
  4525. this.path_symlink = function (oldPath, oldPathLen, fd, newPath, newPathLen) {
  4526. var Result = 0;
  4527. var lOld = "";
  4528. var lNew = "";
  4529. lOld = this.GetUTF8StringFromMem(oldPath,oldPathLen);
  4530. lNew = this.GetUTF8StringFromMem(newPath,newPathLen);
  4531. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_symlink('%s',%d,'%s')",pas.System.VarRecs(18,lOld,19,fd,18,lNew));
  4532. if (!(this.FWasiFS != null)) {
  4533. Result = 52}
  4534. else try {
  4535. Result = this.FWasiFS.SymLinkAt(fd,lOld,lNew);
  4536. } catch ($e) {
  4537. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4538. var E = $e;
  4539. Result = this.$class.ErrorToCode(E);
  4540. } else throw $e
  4541. };
  4542. return Result;
  4543. };
  4544. this.path_unlink_file = function (fd, pathPtr, pathLen) {
  4545. var Result = 0;
  4546. var lPath = "";
  4547. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4548. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_unlink_file(%d,'%s')",pas.System.VarRecs(19,fd,18,lPath));
  4549. if (!(this.FWasiFS != null)) {
  4550. Result = 52}
  4551. else try {
  4552. Result = this.FWasiFS.UnLinkAt(fd,lPath);
  4553. } catch ($e) {
  4554. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4555. var E = $e;
  4556. Result = this.$class.ErrorToCode(E);
  4557. } else throw $e
  4558. };
  4559. return Result;
  4560. };
  4561. var TagOffset = 8;
  4562. var TimeoutOffset = 24;
  4563. var PrecisionOffset = 32;
  4564. this.poll_oneoff = function (sin, sout, nsubscriptions, nevents) {
  4565. var Result = 0;
  4566. var Tag = 0;
  4567. var Precision = null;
  4568. var TimeOut = null;
  4569. var msTimeOut = null;
  4570. var msTimeout32 = 0;
  4571. var arr = null;
  4572. var mem = null;
  4573. Tag = this.GetMemInfoInt8(sin + 8);
  4574. if (Tag === 0) {
  4575. mem = this.getModuleMemoryDataView();
  4576. TimeOut = mem.getBigInt64(sin + 24,true);
  4577. Precision = mem.getBigInt64(sin + 32,true);
  4578. msTimeOut = TimeOut / Precision;
  4579. arr = new Int32Array(this.FMemory.buffer);
  4580. Atomics.store(arr,256,0);
  4581. msTimeout32 = pas.SysUtils.StrToInt(msTimeOut.toString());
  4582. Atomics.wait(arr,256,0,msTimeout32);
  4583. };
  4584. Result = 0;
  4585. return Result;
  4586. };
  4587. this.proc_exit = function (rval) {
  4588. var Result = 0;
  4589. this.FExitCode = rval;
  4590. Result = 0;
  4591. return Result;
  4592. };
  4593. this.proc_raise = function (sig) {
  4594. var Result = 0;
  4595. console.log("Unimplemented: TPas2JSWASIEnvironment.proc_raise");
  4596. Result = 52;
  4597. return Result;
  4598. };
  4599. this.random_get = function (bufPtr, bufLen) {
  4600. var Result = 0;
  4601. var arr = null;
  4602. var I = 0;
  4603. var View = null;
  4604. arr = new Uint8Array(bufLen);
  4605. crypto.getRandomValues(arr);
  4606. View = this.getModuleMemoryDataView();
  4607. for (var $l = 0, $end = arr.length - 1; $l <= $end; $l++) {
  4608. I = $l;
  4609. View.setInt8(bufPtr + I,arr[I]);
  4610. };
  4611. Result = 0;
  4612. return Result;
  4613. };
  4614. this.sched_yield = function () {
  4615. var Result = 0;
  4616. Result = 0;
  4617. return Result;
  4618. };
  4619. this.sock_recv = function () {
  4620. var Result = 0;
  4621. console.log("Unimplemented: TPas2JSWASIEnvironment.sock_recv");
  4622. Result = 52;
  4623. return Result;
  4624. };
  4625. this.sock_send = function () {
  4626. var Result = 0;
  4627. console.log("Unimplemented: TPas2JSWASIEnvironment.sock_recv");
  4628. Result = 52;
  4629. return Result;
  4630. };
  4631. this.sock_shutdown = function () {
  4632. var Result = 0;
  4633. console.log("Unimplemented: TPas2JSWASIEnvironment.sock_shutdown");
  4634. Result = 52;
  4635. return Result;
  4636. };
  4637. this.SetMemory = function (aMemory) {
  4638. this.FMemory = aMemory;
  4639. };
  4640. this.Create$1 = function () {
  4641. var I = 0;
  4642. this.FWASIImportName = "wasi_snapshot_preview1";
  4643. this.FArguments = pas.Classes.TStringList.$create("Create$1");
  4644. this.FEnvironment = pas.Classes.TStringList.$create("Create$1");
  4645. for (var $l = 0, $end = pas.SysUtils.GetEnvironmentVariableCount() - 1; $l <= $end; $l++) {
  4646. I = $l;
  4647. this.FEnvironment.Add(pas.SysUtils.GetEnvironmentString(I));
  4648. };
  4649. return this;
  4650. };
  4651. this.Destroy = function () {
  4652. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4653. return this.p.FEnvironment;
  4654. }, set: function (v) {
  4655. this.p.FEnvironment = v;
  4656. }});
  4657. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4658. return this.p.FArguments;
  4659. }, set: function (v) {
  4660. this.p.FArguments = v;
  4661. }});
  4662. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4663. return this.p.FImportExtensions;
  4664. }, set: function (v) {
  4665. this.p.FImportExtensions = v;
  4666. }});
  4667. pas.System.TObject.Destroy.call(this);
  4668. };
  4669. this.GetUTF8StringFromMem = function (aLoc, aLen) {
  4670. var Result = "";
  4671. var tmpBuf = null;
  4672. tmpBuf = pas.JS.SharedToNonShared(this.getModuleMemoryDataView().buffer.slice(aLoc,aLoc + aLen));
  4673. Result = this.UTF8TextDecoder.decode(tmpBuf);
  4674. return Result;
  4675. };
  4676. this.GetUTF8StringFromArray = function (aSourceArray) {
  4677. var Result = "";
  4678. var TmpBytes = null;
  4679. TmpBytes = pas.JS.SharedToNonShared$1(aSourceArray,false);
  4680. Result = this.UTF8TextDecoder.decode(TmpBytes);
  4681. return Result;
  4682. };
  4683. this.SetUTF8StringInMem = function (aLoc, aLen, AString) {
  4684. var Result = 0;
  4685. var Arr = null;
  4686. Arr = this.UTF8TextEncoder.encode(AString);
  4687. if (Arr.byteLength > aLen) {
  4688. Result = -Arr.byteLength}
  4689. else if (Arr.byteLength === 0) {
  4690. Result = 0}
  4691. else Result = this.SetUTF8StringInMem$1(aLoc,aLen,Arr);
  4692. return Result;
  4693. };
  4694. this.SetUTF8StringInMem$1 = function (aLoc, aLen, AStringBuf) {
  4695. var Result = 0;
  4696. var Arr = null;
  4697. if (AStringBuf == null) return 0;
  4698. Arr = new Uint8Array(this.getModuleMemoryDataView().buffer,aLoc,aLen);
  4699. Arr.set(AStringBuf);
  4700. Result = AStringBuf.byteLength;
  4701. return Result;
  4702. };
  4703. this.SetMemInfoInt32 = function (aLoc, aValue) {
  4704. var Result = 0;
  4705. var View = null;
  4706. View = this.getModuleMemoryDataView();
  4707. View.setInt32(aLoc,aValue,true);
  4708. Result = aLoc + 4;
  4709. return Result;
  4710. };
  4711. this.SetMemInfoInt64 = function (aLoc, aValue) {
  4712. var Result = 0;
  4713. var View = null;
  4714. View = this.getModuleMemoryDataView();
  4715. this.$class.setBigInt64(View,aLoc,aValue,true);
  4716. Result = aLoc + 8;
  4717. return Result;
  4718. };
  4719. this.SetMemInfoUInt8 = function (aLoc, aValue) {
  4720. var Result = 0;
  4721. var View = null;
  4722. View = this.getModuleMemoryDataView();
  4723. View.setUint8(aLoc,aValue);
  4724. Result = aLoc + 1;
  4725. return Result;
  4726. };
  4727. this.SetMemInfoUInt32 = function (aLoc, aValue) {
  4728. var Result = 0;
  4729. var View = null;
  4730. View = this.getModuleMemoryDataView();
  4731. View.setUint32(aLoc,aValue,true);
  4732. Result = aLoc + 4;
  4733. return Result;
  4734. };
  4735. this.SetMemInfoUInt64 = function (aLoc, aValue) {
  4736. var Result = 0;
  4737. var View = null;
  4738. View = this.getModuleMemoryDataView();
  4739. this.$class.setBigUint64(View,aLoc,aValue,true);
  4740. Result = aLoc + 8;
  4741. return Result;
  4742. };
  4743. this.GetMemInfoInt8 = function (aLoc) {
  4744. var Result = 0;
  4745. var View = null;
  4746. View = this.getModuleMemoryDataView();
  4747. Result = View.getInt8(aLoc);
  4748. return Result;
  4749. };
  4750. this.GetMemInfoInt32 = function (aLoc) {
  4751. var Result = 0;
  4752. var View = null;
  4753. View = this.getModuleMemoryDataView();
  4754. Result = View.getInt32(aLoc,true);
  4755. return Result;
  4756. };
  4757. this.AddImports = function (aObject) {
  4758. var Ext = null;
  4759. var I = 0;
  4760. var O = null;
  4761. aObject[this.FWASIImportName] = this.GetImportObject();
  4762. if (this.FImportExtensions != null) for (var $l = 0, $end = this.FImportExtensions.FCount - 1; $l <= $end; $l++) {
  4763. I = $l;
  4764. Ext = rtl.getObject(this.FImportExtensions.Get(I));
  4765. O = new Object();
  4766. Ext.FillImportObject(O);
  4767. aObject[Ext.ImportName()] = O;
  4768. };
  4769. };
  4770. this.SetExports = function (aExports) {
  4771. var Ext = null;
  4772. var I = 0;
  4773. if (this.FImportExtensions != null) for (var $l = 0, $end = this.FImportExtensions.FCount - 1; $l <= $end; $l++) {
  4774. I = $l;
  4775. Ext = rtl.getObject(this.FImportExtensions.Get(I));
  4776. Ext.SetInstanceExports(aExports);
  4777. };
  4778. };
  4779. });
  4780. rtl.createClass(this,"TImportExtension",pas.System.TObject,function () {
  4781. this.$init = function () {
  4782. pas.System.TObject.$init.call(this);
  4783. this.FEnv = null;
  4784. this.FInstanceExports = null;
  4785. };
  4786. this.$final = function () {
  4787. this.FEnv = undefined;
  4788. this.FInstanceExports = undefined;
  4789. pas.System.TObject.$final.call(this);
  4790. };
  4791. this.SetInstanceExports = function (AValue) {
  4792. if (this.FInstanceExports === AValue) return;
  4793. this.FInstanceExports = AValue;
  4794. };
  4795. this.Create$1 = function (aEnv) {
  4796. this.FEnv = aEnv;
  4797. if (this.FEnv != null) this.FEnv.AddExtension(this);
  4798. return this;
  4799. };
  4800. this.Destroy = function () {
  4801. if (this.FEnv != null) this.FEnv.RemoveExtension(this);
  4802. pas.System.TObject.Destroy.call(this);
  4803. };
  4804. this.RegisterName = function () {
  4805. var Result = "";
  4806. Result = this.$classname;
  4807. return Result;
  4808. };
  4809. });
  4810. rtl.createClass(this,"TImportExtensionRegistry",pas.System.TObject,function () {
  4811. this._Instance = null;
  4812. this.$init = function () {
  4813. pas.System.TObject.$init.call(this);
  4814. this.FExtensions = [];
  4815. this.FExtensionCount = 0;
  4816. };
  4817. this.$final = function () {
  4818. this.FExtensions = undefined;
  4819. pas.System.TObject.$final.call(this);
  4820. };
  4821. this.Grow = function () {
  4822. this.FExtensions = rtl.arraySetLength(this.FExtensions,null,rtl.length(this.FExtensions) + 1);
  4823. };
  4824. this.create$1 = function () {
  4825. this.FExtensionCount = 0;
  4826. this.Grow();
  4827. return this;
  4828. };
  4829. this.Destroy = function () {
  4830. pas.System.TObject.Destroy.call(this);
  4831. };
  4832. this.GetExtensions = function () {
  4833. var Result = [];
  4834. Result = rtl.arrayCopy(0,this.FExtensions,0,this.FExtensionCount);
  4835. return Result;
  4836. };
  4837. });
  4838. rtl.recNewT(this,"TWebAssemblyStartDescriptor",function () {
  4839. this.Module = null;
  4840. this.Memory = null;
  4841. this.Table = null;
  4842. this.Exported = null;
  4843. this.Imports = null;
  4844. this.Instance = null;
  4845. this.CallRun = null;
  4846. this.RunExceptionClass = "";
  4847. this.RunExceptionMessage = "";
  4848. this.$eq = function (b) {
  4849. return (this.Module === b.Module) && (this.Memory === b.Memory) && (this.Table === b.Table) && (this.Exported === b.Exported) && (this.Imports === b.Imports) && (this.Instance === b.Instance) && rtl.eqCallback(this.CallRun,b.CallRun) && (this.RunExceptionClass === b.RunExceptionClass) && (this.RunExceptionMessage === b.RunExceptionMessage);
  4850. };
  4851. this.$assign = function (s) {
  4852. this.Module = s.Module;
  4853. this.Memory = s.Memory;
  4854. this.Table = s.Table;
  4855. this.Exported = s.Exported;
  4856. this.Imports = s.Imports;
  4857. this.Instance = s.Instance;
  4858. this.CallRun = s.CallRun;
  4859. this.RunExceptionClass = s.RunExceptionClass;
  4860. this.RunExceptionMessage = s.RunExceptionMessage;
  4861. return this;
  4862. };
  4863. });
  4864. rtl.createClass(this,"TWASIHost",pas.Classes.TComponent,function () {
  4865. this.$init = function () {
  4866. pas.Classes.TComponent.$init.call(this);
  4867. this.FAfterInstantation = null;
  4868. this.FAfterStart = null;
  4869. this.FAutoCreateExtensions = false;
  4870. this.FBeforeInstantation = null;
  4871. this.FBeforeStart = null;
  4872. this.FConvertNativeExceptions = false;
  4873. this.FEnv = null;
  4874. this.FExcludeExtensions = null;
  4875. this.FExported = null;
  4876. this.FOnAllExtensionsCreated = null;
  4877. this.FOnExtensionCreated = null;
  4878. this.FOnInstantiateFail = null;
  4879. this.FOnLoadFail = null;
  4880. this.FOnWasmException = null;
  4881. this.FPreparedStartDescriptor = $mod.TWebAssemblyStartDescriptor.$new();
  4882. this.FMemoryDescriptor = pas.webassembly.TJSWebAssemblyMemoryDescriptor.$new();
  4883. this.FOnConsoleRead = null;
  4884. this.FOnConsoleWrite = null;
  4885. this.FPredefinedConsoleInput = null;
  4886. this.FReadLineCount = 0;
  4887. this.FRunEntryFunction = "";
  4888. this.FTableDescriptor = pas.webassembly.TJSWebAssemblyTableDescriptor.$new();
  4889. this.FExtensions = [];
  4890. };
  4891. this.$final = function () {
  4892. this.FAfterInstantation = undefined;
  4893. this.FAfterStart = undefined;
  4894. this.FBeforeInstantation = undefined;
  4895. this.FBeforeStart = undefined;
  4896. this.FEnv = undefined;
  4897. this.FExcludeExtensions = undefined;
  4898. this.FExported = undefined;
  4899. this.FOnAllExtensionsCreated = undefined;
  4900. this.FOnExtensionCreated = undefined;
  4901. this.FOnInstantiateFail = undefined;
  4902. this.FOnLoadFail = undefined;
  4903. this.FOnWasmException = undefined;
  4904. this.FPreparedStartDescriptor = undefined;
  4905. this.FMemoryDescriptor = undefined;
  4906. this.FOnConsoleRead = undefined;
  4907. this.FOnConsoleWrite = undefined;
  4908. this.FPredefinedConsoleInput = undefined;
  4909. this.FTableDescriptor = undefined;
  4910. this.FExtensions = undefined;
  4911. pas.Classes.TComponent.$final.call(this);
  4912. };
  4913. this.GetEnv = function () {
  4914. var Result = null;
  4915. if (this.FEnv === null) {
  4916. this.FEnv = this.CreateWasiEnvironment();
  4917. this.FEnv.FOnStdErrorWrite = rtl.createCallback(this,"DoStdWrite");
  4918. this.FEnv.FOnStdOutputWrite = rtl.createCallback(this,"DoStdWrite");
  4919. this.FEnv.FOnGetConsoleInputString = rtl.createCallback(this,"DoStdRead");
  4920. if (this.FAutoCreateExtensions) this.CreateStandardExtensions();
  4921. };
  4922. Result = this.FEnv;
  4923. return Result;
  4924. };
  4925. this.NeedSharedMemory = function () {
  4926. var Result = false;
  4927. Result = false;
  4928. return Result;
  4929. };
  4930. this.ConvertWasmException = function () {
  4931. var Result = false;
  4932. var lInfo = $mod.TLastExceptionInfo.$new();
  4933. lInfo.$assign($mod.TLastExceptionInfo.$new());
  4934. Result = !this.GetExceptionInfo(lInfo);
  4935. if (Result) return Result;
  4936. lInfo.doraise = true;
  4937. if (this.FOnWasmException != null) this.FOnWasmException(this,lInfo);
  4938. if (lInfo.doraise) throw $mod.EWasmNativeException.$create("create$2",[lInfo.ClassName,lInfo.Message]);
  4939. return Result;
  4940. };
  4941. this.WrapExports = function (aExported) {
  4942. var $Self = this;
  4943. var Result = null;
  4944. function createwrapper(aScope, aFunc) {
  4945. var Result = undefined;
  4946. Result = function () {
  4947. var Result = undefined;
  4948. Result = undefined;
  4949. try {
  4950. Result=aFunc.apply(aScope,arguments);
  4951. } catch ($e) {
  4952. if (rtl.isExt($e,WebAssembly.Exception)) {
  4953. var E = $e;
  4954. if ($Self.ConvertWasmException()) throw $e;
  4955. } else throw $e
  4956. };
  4957. return Result;
  4958. };
  4959. return Result;
  4960. };
  4961. var S = "";
  4962. var lFunc = undefined;
  4963. var LNew = null;
  4964. LNew = new Object();
  4965. for (var $in = Object.getOwnPropertyNames(aExported), $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  4966. S = $in[$l];
  4967. lFunc = aExported[S];
  4968. if (!rtl.isFunction(lFunc) || (S === "GetLastExceptionInfo") || (S === "FreeLastExceptionInfo")) {
  4969. LNew[S] = lFunc}
  4970. else LNew[S] = createwrapper(this,lFunc);
  4971. };
  4972. Result = LNew;
  4973. return Result;
  4974. };
  4975. this.DeleteExtensions = function () {
  4976. var I = 0;
  4977. for (var $l = 0, $end = rtl.length(this.FExtensions) - 1; $l <= $end; $l++) {
  4978. I = $l;
  4979. pas.SysUtils.FreeAndNil({a: I, p: this.FExtensions, get: function () {
  4980. return this.p[this.a];
  4981. }, set: function (v) {
  4982. this.p[this.a] = v;
  4983. }});
  4984. };
  4985. this.FExtensions = rtl.arraySetLength(this.FExtensions,null,0);
  4986. };
  4987. this.DoCreateStandardExtensions = function () {
  4988. var lCount = 0;
  4989. var lClass = null;
  4990. var lClasses = [];
  4991. this.DeleteExtensions();
  4992. lClasses = $mod.TImportExtensionRegistry._Instance.GetExtensions();
  4993. this.FExtensions = rtl.arraySetLength(this.FExtensions,null,rtl.length(lClasses));
  4994. lCount = 0;
  4995. for (var $in = lClasses, $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  4996. lClass = $in[$l];
  4997. if ((this.FExcludeExtensions.IndexOf(lClass.RegisterName()) === -1) && (this.FExcludeExtensions.IndexOf(lClass.$classname) === -1)) {
  4998. this.FExtensions[lCount] = this.CreateStandardExtension(lClass);
  4999. lCount += 1;
  5000. };
  5001. };
  5002. };
  5003. this.CreateStandardExtension = function (aClass) {
  5004. var Result = null;
  5005. Result = aClass.$create("Create");
  5006. if (this.FOnExtensionCreated != null) this.FOnExtensionCreated(this,Result);
  5007. return Result;
  5008. };
  5009. this.DoAfterInstantiate = function () {
  5010. if (this.FAfterInstantation != null) this.FAfterInstantation(this);
  5011. };
  5012. this.DoBeforeInstantiate = function () {
  5013. if (this.FBeforeInstantation != null) this.FBeforeInstantation(this);
  5014. };
  5015. this.DoLoadFail = function (aError) {
  5016. if (this.FOnLoadFail != null) this.FOnLoadFail(this,aError);
  5017. };
  5018. this.DoInstantiateFail = function (aError) {
  5019. if (this.FOnInstantiateFail != null) this.FOnInstantiateFail(this,aError);
  5020. };
  5021. this.RunWebAssemblyInstance = function (aBeforeStart, aAfterStart, aRun) {
  5022. var Result = false;
  5023. Result = true;
  5024. if (aBeforeStart != null) Result = aBeforeStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor));
  5025. if (this.FBeforeStart != null) this.FBeforeStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor),{get: function () {
  5026. return Result;
  5027. }, set: function (v) {
  5028. Result = v;
  5029. }});
  5030. if (!Result) return Result;
  5031. try {
  5032. if (aRun === null) aRun = this.FPreparedStartDescriptor.CallRun;
  5033. aRun(this.FPreparedStartDescriptor.Exported);
  5034. if (aAfterStart != null) aAfterStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor));
  5035. if (this.FAfterStart != null) this.FAfterStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor));
  5036. } catch ($e) {
  5037. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  5038. var E = $e;
  5039. this.FPreparedStartDescriptor.RunExceptionClass = E.$classname;
  5040. this.FPreparedStartDescriptor.RunExceptionMessage = E.fMessage;
  5041. } else if (rtl.isExt($e,Error)) {
  5042. var JE = $e;
  5043. this.FPreparedStartDescriptor.RunExceptionClass = typeof(JE);
  5044. this.FPreparedStartDescriptor.RunExceptionMessage = JE.message;
  5045. } else if (rtl.isExt($e,Object)) {
  5046. var OE = $e;
  5047. this.FPreparedStartDescriptor.RunExceptionClass = typeof(OE);
  5048. this.FPreparedStartDescriptor.RunExceptionMessage = JSON.stringify(OE);
  5049. } else throw $e
  5050. };
  5051. if (this.FPreparedStartDescriptor.RunExceptionClass !== "") console.error("Running Webassembly resulted in exception. Exception class: ",this.FPreparedStartDescriptor.RunExceptionClass,", message:",this.FPreparedStartDescriptor.RunExceptionMessage);
  5052. return Result;
  5053. };
  5054. this.DoStdRead = function (Sender, AInput) {
  5055. var S = "";
  5056. S = "";
  5057. if (this.FOnConsoleRead != null) {
  5058. this.FOnConsoleRead(this,{get: function () {
  5059. return S;
  5060. }, set: function (v) {
  5061. S = v;
  5062. }})}
  5063. else {
  5064. if (this.FReadLineCount < this.FPredefinedConsoleInput.GetCount()) {
  5065. S = this.FPredefinedConsoleInput.Get(this.FReadLineCount);
  5066. this.FReadLineCount += 1;
  5067. };
  5068. };
  5069. AInput.set(S);
  5070. };
  5071. this.DoStdWrite = function (Sender, aOutput) {
  5072. this.WriteOutput(aOutput);
  5073. };
  5074. this.CreateWebAssembly = function (aPath, aImportObject) {
  5075. var $Self = this;
  5076. var Result = null;
  5077. function InstantiateOK(Res) {
  5078. var Result = undefined;
  5079. Result = Res;
  5080. return Result;
  5081. };
  5082. function InstantiateFail(Res) {
  5083. var Result = undefined;
  5084. Result = false;
  5085. console.log("Instantiating of WebAssembly from " + aPath + " failed " + $impl.ValueToMessage(Res));
  5086. $Self.DoInstantiateFail(Res);
  5087. return Result;
  5088. };
  5089. function ArrayOK(res2) {
  5090. var Result = undefined;
  5091. $Self.DoBeforeInstantiate();
  5092. Result = WebAssembly.instantiate(res2,aImportObject).then(InstantiateOK,InstantiateFail);
  5093. return Result;
  5094. };
  5095. function DoFail(res) {
  5096. var Result = undefined;
  5097. Result = false;
  5098. console.log('Loading of WebAssembly from URL "' + aPath + '" failed: ' + $impl.ValueToMessage(res));
  5099. $Self.DoLoadFail(res);
  5100. return Result;
  5101. };
  5102. function fetchOK(res) {
  5103. var Result = undefined;
  5104. if (rtl.trunc(res.status / 100) !== 2) {
  5105. $Self.DoLoadFail(res);
  5106. throw new Error('Loading of WebAssembly from URL "' + aPath + '" failed: status: ' + pas.SysUtils.IntToStr(res.status) + " " + res.statusText);
  5107. } else Result = res.arrayBuffer().then(ArrayOK,null);
  5108. return Result;
  5109. };
  5110. Result = fetch(aPath).then(fetchOK,DoFail);
  5111. return Result;
  5112. };
  5113. this.CreateWasiEnvironment = function () {
  5114. var Result = null;
  5115. Result = $mod.TPas2JSWASIEnvironment.$create("Create$1");
  5116. return Result;
  5117. };
  5118. this.GetTable = function () {
  5119. var Result = null;
  5120. Result = new WebAssembly.Table(pas.webassembly.TJSWebAssemblyTableDescriptor.$clone(this.FTableDescriptor));
  5121. return Result;
  5122. };
  5123. this.GetMemory = function () {
  5124. var Result = null;
  5125. Result = new WebAssembly.Memory(pas.webassembly.TJSWebAssemblyMemoryDescriptor.$clone(this.FMemoryDescriptor));
  5126. return Result;
  5127. };
  5128. this.Create$1 = function (aOwner) {
  5129. pas.Classes.TComponent.Create$1.call(this,aOwner);
  5130. this.FMemoryDescriptor.initial = 256;
  5131. this.FMemoryDescriptor.maximum = 256;
  5132. this.FMemoryDescriptor.shared = this.$class.NeedSharedMemory();
  5133. this.FTableDescriptor.initial = 0;
  5134. this.FTableDescriptor.maximum = 0;
  5135. this.FTableDescriptor.element = "anyfunc";
  5136. this.FPredefinedConsoleInput = pas.Classes.TStringList.$create("Create$1");
  5137. this.FExcludeExtensions = pas.Classes.TStringList.$create("Create$1");
  5138. this.FConvertNativeExceptions = true;
  5139. return this;
  5140. };
  5141. this.Destroy = function () {
  5142. pas.SysUtils.FreeAndNil({p: this, get: function () {
  5143. return this.p.FExcludeExtensions;
  5144. }, set: function (v) {
  5145. this.p.FExcludeExtensions = v;
  5146. }});
  5147. pas.SysUtils.FreeAndNil({p: this, get: function () {
  5148. return this.p.FPredefinedConsoleInput;
  5149. }, set: function (v) {
  5150. this.p.FPredefinedConsoleInput = v;
  5151. }});
  5152. pas.SysUtils.FreeAndNil({p: this, get: function () {
  5153. return this.p.FEnv;
  5154. }, set: function (v) {
  5155. this.p.FEnv = v;
  5156. }});
  5157. pas.Classes.TComponent.Destroy.call(this);
  5158. };
  5159. this.CreateStandardExtensions = function () {
  5160. this.DoCreateStandardExtensions();
  5161. if (this.FOnAllExtensionsCreated != null) this.FOnAllExtensionsCreated(this);
  5162. };
  5163. this.GetExceptionInfo = function (aInfo) {
  5164. var Result = false;
  5165. var lPtr = 0;
  5166. var lPointer = 0;
  5167. var lString = 0;
  5168. var lLen = 0;
  5169. var lVal = undefined;
  5170. var lVal2 = undefined;
  5171. Result = false;
  5172. lVal = this.FExported["GetLastExceptionInfo"];
  5173. lVal2 = this.FExported["FreeLastExceptionInfo"];
  5174. if (!(pas.JS.isDefined(lVal) && pas.JS.isDefined(lVal2))) return Result;
  5175. lPointer = lVal();
  5176. if (lPointer === 0) return Result;
  5177. lPtr = lPointer;
  5178. lString = this.GetEnv().GetMemInfoInt32(lPtr);
  5179. lPtr += 4;
  5180. lLen = this.GetEnv().GetMemInfoInt32(lPtr);
  5181. lPtr += 4;
  5182. aInfo.ClassName = this.GetEnv().GetUTF8StringFromMem(lString,lLen);
  5183. lString = this.GetEnv().GetMemInfoInt32(lPtr);
  5184. lPtr += 4;
  5185. lLen = this.GetEnv().GetMemInfoInt32(lPtr);
  5186. lPtr += 4;
  5187. aInfo.Message = this.GetEnv().GetUTF8StringFromMem(lString,lLen);
  5188. aInfo.more = this.GetEnv().GetMemInfoInt8(lPtr) !== 0;
  5189. lVal2(lPointer);
  5190. Result = true;
  5191. return Result;
  5192. };
  5193. this.WriteOutput = function (aOutput) {
  5194. if (this.FOnConsoleWrite != null) {
  5195. this.FOnConsoleWrite(this,aOutput)}
  5196. else pas.System.Writeln(aOutput);
  5197. };
  5198. this.PrepareWebAssemblyInstance = function (aDescr) {
  5199. if (this.FConvertNativeExceptions) aDescr.Exported = this.WrapExports(aDescr.Exported);
  5200. this.FPreparedStartDescriptor.$assign(aDescr);
  5201. this.FExported = this.FPreparedStartDescriptor.Exported;
  5202. this.GetEnv().SetInstance(aDescr.Instance);
  5203. this.GetEnv().SetMemory(aDescr.Memory);
  5204. this.GetEnv().SetExports(this.FExported);
  5205. this.DoAfterInstantiate();
  5206. };
  5207. this.InitStartDescriptor = function (aMemory, aTable, aImportObj) {
  5208. var Result = $mod.TWebAssemblyStartDescriptor.$new();
  5209. Result.Memory = aMemory;
  5210. Result.Table = aTable;
  5211. if (!(aImportObj != null)) aImportObj = new Object();
  5212. aImportObj["env"] = pas.JS.New(["memory",Result.Memory,"tbl",Result.Table]);
  5213. this.GetEnv().AddImports(aImportObj);
  5214. Result.Imports = aImportObj;
  5215. return Result;
  5216. };
  5217. this.StartWebAssembly = function (aPath, DoRun, aBeforeStart, aAfterStart) {
  5218. var $Self = this;
  5219. var Result = null;
  5220. var WASD = $mod.TWebAssemblyStartDescriptor.$new();
  5221. function InitEnv(aValue) {
  5222. var Result = undefined;
  5223. if (!(typeof(aValue) === "object")) throw $mod.EWasiError.$create("Create$1",["Did not get a instantiated webassembly"]);
  5224. WASD.Instance = aValue.instance;
  5225. WASD.Module = aValue.module;
  5226. WASD.Exported = WASD.Instance.exports;
  5227. WASD.CallRun = function (aExports) {
  5228. if ($Self.FRunEntryFunction === "") {
  5229. if (aExports["_initialize"] != null) {
  5230. aExports._initialize()}
  5231. else aExports._start()}
  5232. else aExports[$Self.FRunEntryFunction]();
  5233. };
  5234. $Self.PrepareWebAssemblyInstance($mod.TWebAssemblyStartDescriptor.$clone(WASD));
  5235. if (DoRun) $Self.RunWebAssemblyInstance(aBeforeStart,aAfterStart,null);
  5236. Result = Promise.resolve($mod.TWebAssemblyStartDescriptor.$clone(WASD));
  5237. return Result;
  5238. };
  5239. function DoFail(aValue) {
  5240. var Result = undefined;
  5241. Result = true;
  5242. console.log("Failed to create webassembly. Reason:");
  5243. console.debug(aValue);
  5244. if (rtl.isObject(aValue)) throw aValue;
  5245. return Result;
  5246. };
  5247. this.FReadLineCount = 0;
  5248. this.FPreparedStartDescriptor.$assign($mod.TWebAssemblyStartDescriptor.$new());
  5249. WASD.$assign(this.InitStartDescriptor(this.GetMemory(),this.GetTable(),null));
  5250. Result = this.CreateWebAssembly(aPath,WASD.Imports).then(InitEnv,DoFail);
  5251. return Result;
  5252. };
  5253. });
  5254. $mod.$implcode = function () {
  5255. $impl.ValueToMessage = function (Res) {
  5256. var Result = "";
  5257. if (rtl.isObject(Res)) {
  5258. Result = rtl.getObject(Res).$classname;
  5259. if (pas.SysUtils.Exception.isPrototypeOf(rtl.getObject(Res))) Result = Result + ": " + rtl.getObject(Res).fMessage;
  5260. };
  5261. if ((typeof(Res) === "object") && Res.hasOwnProperty("message")) {
  5262. Result = "" + Res["message"]}
  5263. else Result = JSON.stringify(Res);
  5264. return Result;
  5265. };
  5266. $impl.toUTF8Array = function (str) {
  5267. var Result = null;
  5268. var Len = 0;
  5269. var I = 0;
  5270. var P = 0;
  5271. var charCode = 0;
  5272. function push(abyte) {
  5273. Result[P] = abyte;
  5274. P += 1;
  5275. };
  5276. Result = new Uint8Array(str.length * 4);
  5277. P = 0;
  5278. Len = str.length;
  5279. I = 1;
  5280. while (I <= Len) {
  5281. charCode = str.charCodeAt(I - 1);
  5282. if (charCode < 0x80) {
  5283. push(charCode)}
  5284. else if (charCode < 0x800) {
  5285. push(rtl.or(0xc0,Math.floor(charCode / 64)));
  5286. push(rtl.or(0x80,charCode & 0x3f));
  5287. } else if ((charCode < 0xd800) || (charCode >= 0xe000)) {
  5288. push(rtl.or(0xe0,Math.floor(charCode / 4096)));
  5289. push(rtl.or(0x80,Math.floor(charCode / 64) & 0x3f));
  5290. push(rtl.or(0x80,charCode & 0x3f));
  5291. } else {
  5292. I += 1;
  5293. charCode = 0x10000 + rtl.or(rtl.shl(charCode & 0x3ff,10),str.charCodeAt(I - 1) & 0x3ff);
  5294. push(rtl.or(0xf0,Math.floor(charCode / 262144)));
  5295. push(rtl.or(0x80,Math.floor(charCode / 4096) & 0x3f));
  5296. push(rtl.or(0x80,Math.floor(charCode / 64) & 0x3f));
  5297. push(rtl.or(0x80,charCode & 0x3f));
  5298. };
  5299. I += 1;
  5300. };
  5301. Result = Result.slice(0,P);
  5302. return Result;
  5303. };
  5304. };
  5305. $mod.$init = function () {
  5306. (function () {
  5307. var Opts = null;
  5308. Opts = new Object();
  5309. Opts.ignoreBOM = true;
  5310. Opts.fatal = true;
  5311. $mod.TPas2JSWASIEnvironment.UTF8TextDecoder = new TextDecoder("utf-8",Opts);
  5312. $mod.TPas2JSWASIEnvironment.UTF8TextEncoder = new TextEncoder();
  5313. })();
  5314. (function () {
  5315. $mod.TImportExtensionRegistry._Instance = $mod.TImportExtensionRegistry.$create("create$1");
  5316. })();
  5317. };
  5318. },["weborworker"]);
  5319. rtl.module("Rtl.WebThreads",["System","JS","SysUtils","wasienv","webassembly","Rtl.WorkerCommands"],function () {
  5320. "use strict";
  5321. var $mod = this;
  5322. this.cmdConsole = "console";
  5323. this.cmdCleanup = "cleanup";
  5324. this.cmdCancel = "cancel";
  5325. this.cmdLoaded = "loaded";
  5326. this.cmdKill = "kill";
  5327. this.cmdSpawn = "spawn";
  5328. this.cmdLoad = "load";
  5329. this.cmdRun = "run";
  5330. this.cmdExecute = "execute";
  5331. this.cmdRPC = "rpc";
  5332. this.cmdRPCResult = "rpcresult";
  5333. this.cmdReady = "ready";
  5334. this.DefaultThreadWorker = "pas2jsthreadworker.js";
  5335. this.DefaultThreadCount = 2;
  5336. this.DefaultMaxWorkerCount = 100;
  5337. this.sThreadSpawn = "thread-spawn";
  5338. this.sThreadSelf = "thread_self";
  5339. rtl.createClass(this,"EWasmThreads",pas.SysUtils.Exception,function () {
  5340. });
  5341. rtl.createHelper(this,"TWorkerCommandHelper",pas["Rtl.WorkerCommands"].TCustomWorkerCommandHelper,function () {
  5342. this.NewWorker = function (aCommand, aThreadID) {
  5343. var Result = null;
  5344. if (aThreadID === -1) {
  5345. Result = pas["Rtl.WorkerCommands"].TCustomWorkerCommandHelper.createCommand(aCommand,"")}
  5346. else {
  5347. Result = pas["Rtl.WorkerCommands"].TCustomWorkerCommandHelper.createCommand(aCommand,"Wasm thread " + pas.SysUtils.IntToStr(aThreadID));
  5348. Result.ThreadID = aThreadID;
  5349. };
  5350. return Result;
  5351. };
  5352. });
  5353. rtl.createHelper(this,"TWorkerLoadCommandHelper",this.TWorkerCommandHelper,function () {
  5354. this.CommandName = function () {
  5355. var Result = "";
  5356. Result = $mod.cmdLoad;
  5357. return Result;
  5358. };
  5359. this.Create = function (aModule, aMemory) {
  5360. var Result = null;
  5361. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerLoadCommandHelper.CommandName(),-1);
  5362. Result.Memory = aMemory;
  5363. Result.Module = aModule;
  5364. return Result;
  5365. };
  5366. });
  5367. rtl.createHelper(this,"TWorkerRunCommandHelper",this.TWorkerCommandHelper,function () {
  5368. this.CommandName = function () {
  5369. var Result = "";
  5370. Result = $mod.cmdRun;
  5371. return Result;
  5372. };
  5373. this.Create = function (aThreadID, aArgs) {
  5374. var Result = null;
  5375. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerRunCommandHelper.CommandName(),-1);
  5376. Result.ThreadID = aThreadID;
  5377. Result.Args = aArgs;
  5378. return Result;
  5379. };
  5380. });
  5381. rtl.createHelper(this,"TWorkerRpcResultCommandHelper",this.TWorkerCommandHelper,function () {
  5382. this.CommandName = function () {
  5383. var Result = "";
  5384. Result = $mod.cmdRPCResult;
  5385. return Result;
  5386. };
  5387. this.Create = function (aID, aResult) {
  5388. var Result = null;
  5389. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerRpcResultCommandHelper.CommandName(),-1);
  5390. Result.id = aID;
  5391. Result.result = aResult;
  5392. Result.jsonrpc = "2.0";
  5393. return Result;
  5394. };
  5395. this.CreateError = function (aID, aCode, aMessage) {
  5396. var Result = null;
  5397. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerRpcResultCommandHelper.CommandName(),-1);
  5398. Result.id = aID;
  5399. Result.error = new Object();
  5400. Result.error.code = aCode;
  5401. Result.error.message = aMessage;
  5402. Result.jsonrpc = "2.0";
  5403. return Result;
  5404. };
  5405. });
  5406. rtl.recNewT(this,"TThreadinfo",function () {
  5407. this.OriginThreadID = 0;
  5408. this.ThreadID = 0;
  5409. this.Arguments = 0;
  5410. this.$eq = function (b) {
  5411. return (this.OriginThreadID === b.OriginThreadID) && (this.ThreadID === b.ThreadID) && (this.Arguments === b.Arguments);
  5412. };
  5413. this.$assign = function (s) {
  5414. this.OriginThreadID = s.OriginThreadID;
  5415. this.ThreadID = s.ThreadID;
  5416. this.Arguments = s.Arguments;
  5417. return this;
  5418. };
  5419. });
  5420. rtl.createClass(this,"TWasmThreadController",pas.System.TObject,function () {
  5421. this._instanceClass = null;
  5422. this._instance = null;
  5423. this.$init = function () {
  5424. pas.System.TObject.$init.call(this);
  5425. this.FLogAPI = false;
  5426. this.FModule = null;
  5427. this.FMemory = null;
  5428. this.FOnLog = null;
  5429. };
  5430. this.$final = function () {
  5431. this.FModule = undefined;
  5432. this.FMemory = undefined;
  5433. this.FOnLog = undefined;
  5434. pas.System.TObject.$final.call(this);
  5435. };
  5436. this.GetInstance = function () {
  5437. var Result = null;
  5438. if ($mod.TWasmThreadController._instance === null) {
  5439. if ($mod.TWasmThreadController._instanceClass === null) throw $mod.EWasmThreads.$create("Create$1",["No instance class, please include Rtl.ThreadController or Rtl.ThreadWorker unit"]);
  5440. $mod.TWasmThreadController._instance = $mod.TWasmThreadController._instanceClass.$create("create$1");
  5441. };
  5442. Result = $mod.TWasmThreadController._instance;
  5443. return Result;
  5444. };
  5445. this.DoLog = function (msg) {
  5446. if (this.FLogAPI) if (this.FOnLog != null) {
  5447. this.FOnLog(msg)}
  5448. else pas.System.Writeln(msg);
  5449. };
  5450. this.DoLog$1 = function (Fmt, args) {
  5451. this.DoLog(pas.SysUtils.Format(Fmt,args));
  5452. };
  5453. this.create$1 = function () {
  5454. return this;
  5455. };
  5456. this.SetWasmModuleAndMemory = function (aModule, aMemory) {
  5457. this.FModule = aModule;
  5458. this.FMemory = aMemory;
  5459. if ((this.FModule != null) && (this.FMemory != null)) this.HaveWebassembly();
  5460. };
  5461. this.SetInstanceClass = function (aClass) {
  5462. $mod.TWasmThreadController._instanceClass = aClass;
  5463. };
  5464. });
  5465. rtl.createClass(this,"TWasmThreadSupportApi",pas.wasienv.TImportExtension,function () {
  5466. this.thread_spawn = function (start_arg) {
  5467. var Result = 0;
  5468. Result = this.ThreadController().SpawnThread(start_arg);
  5469. return Result;
  5470. };
  5471. this.thread_self = function () {
  5472. var Result = 0;
  5473. var F = null;
  5474. F = this.FInstanceExports["GetSelfThread"];
  5475. if (F != null) {
  5476. Result = F()}
  5477. else Result = 0;
  5478. return Result;
  5479. };
  5480. this.ThreadController = function () {
  5481. var Result = null;
  5482. Result = $mod.TWasmThreadController.GetInstance();
  5483. return Result;
  5484. };
  5485. this.ImportName = function () {
  5486. var Result = "";
  5487. Result = "wasi";
  5488. return Result;
  5489. };
  5490. this.FillImportObject = function (aObject) {
  5491. aObject[$mod.sThreadSpawn] = rtl.createCallback(this,"thread_spawn");
  5492. aObject[$mod.sThreadSelf] = rtl.createCallback(this,"thread_self");
  5493. };
  5494. });
  5495. });
  5496. rtl.module("Rtl.threadcontroller",["System","JS","SysUtils","Rtl.WorkerCommands","Rtl.WebThreads","weborworker"],function () {
  5497. "use strict";
  5498. var $mod = this;
  5499. var $impl = $mod.$impl;
  5500. this.TThreadWorkerState = {"0": "twsInit", twsInit: 0, "1": "twsReady", twsReady: 1, "2": "twsLoadSent", twsLoadSent: 2, "3": "twsIdle", twsIdle: 3, "4": "twsExecuting", twsExecuting: 4};
  5501. rtl.createHelper(this,"TWasmThreadHelper",null,function () {
  5502. this.GetThreadID = function () {
  5503. var Result = 0;
  5504. Result = $mod.TWasmThreadHelper.GetThreadInfo.call(this).ThreadID;
  5505. return Result;
  5506. };
  5507. this.GetThreadInfo = function () {
  5508. var Result = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5509. var S = undefined;
  5510. S = this["FThreadInfo"];
  5511. if (rtl.isObject(S)) {
  5512. Result.$assign(rtl.getObject(S))}
  5513. else Result.$assign(pas["Rtl.WebThreads"].TThreadinfo.$new());
  5514. return Result;
  5515. };
  5516. this.GetWorkerState = function () {
  5517. var Result = 0;
  5518. var S = undefined;
  5519. S = this["FState"];
  5520. if (rtl.isNumber(S)) {
  5521. Result = rtl.trunc(S)}
  5522. else Result = 0;
  5523. return Result;
  5524. };
  5525. this.SetThreadID = function (AValue) {
  5526. $mod.TWasmThreadHelper.GetThreadInfo.call(this).ThreadID = AValue;
  5527. };
  5528. this.SetThreadInfo = function (AValue) {
  5529. this["FThreadInfo"] = AValue;
  5530. };
  5531. this.SetWorkerState = function (AValue) {
  5532. this["FState"] = AValue;
  5533. };
  5534. this.Create = function (aScript) {
  5535. var Result = null;
  5536. Result = new Worker(aScript);
  5537. $mod.TWasmThreadHelper.SetThreadID.call(Result,-1);
  5538. $mod.TWasmThreadHelper.SetWorkerState.call(Result,0);
  5539. $mod.TWasmThreadHelper.SetThreadInfo.call(Result,pas["Rtl.WebThreads"].TThreadinfo.$new());
  5540. return Result;
  5541. };
  5542. this.SendCommand = function (aCommand) {
  5543. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand(this,aCommand);
  5544. };
  5545. });
  5546. rtl.createClass(this,"TThreadController",pas["Rtl.WebThreads"].TWasmThreadController,function () {
  5547. this.$init = function () {
  5548. pas["Rtl.WebThreads"].TWasmThreadController.$init.call(this);
  5549. this.FHandleConsoleMessages = false;
  5550. this.FLogAPI$1 = false;
  5551. this.FOnConsoleWrite = null;
  5552. this.FWorkerCount = 0;
  5553. this.FInitialWorkerCount = 0;
  5554. this.FMaxWorkerCount = 0;
  5555. this.FOnAllocateWorker = null;
  5556. this.FWorkerScript = "";
  5557. this.FIdleWorkers = [];
  5558. this.FBusyWorkers = [];
  5559. this.FThreads = null;
  5560. };
  5561. this.$final = function () {
  5562. this.FOnConsoleWrite = undefined;
  5563. this.FOnAllocateWorker = undefined;
  5564. this.FIdleWorkers = undefined;
  5565. this.FBusyWorkers = undefined;
  5566. this.FThreads = undefined;
  5567. pas["Rtl.WebThreads"].TWasmThreadController.$final.call(this);
  5568. };
  5569. this.HandleRawCleanupCommand = function (aCommand) {
  5570. var lWorker = null;
  5571. lWorker = aCommand._sender;
  5572. this.HandleCleanupCommand(lWorker,aCommand);
  5573. };
  5574. this.HandleRawReadyCommand = function (aCommand) {
  5575. var lWorker = null;
  5576. pas.System.Writeln("Had ready command");
  5577. lWorker = aCommand._sender;
  5578. this.HandleReadyCommand(lWorker,aCommand);
  5579. };
  5580. this.HandleRawSpawnCommand = function (aCommand) {
  5581. var lWorker = null;
  5582. lWorker = aCommand._sender;
  5583. this.HandleSpawnCommand(lWorker,aCommand);
  5584. };
  5585. this.HandleRawLoadedCommand = function (aCommand) {
  5586. var lWorker = null;
  5587. pas.System.Writeln("Receiving loaded command");
  5588. lWorker = aCommand._sender;
  5589. this.HandleLoadedCommand(lWorker,aCommand);
  5590. };
  5591. this.HandleRawConsoleCommand = function (aCommand) {
  5592. var lWorker = null;
  5593. lWorker = aCommand._sender;
  5594. this.HandleConsoleCommand(lWorker,aCommand);
  5595. };
  5596. this.HandleRawKillCommand = function (aCommand) {
  5597. var lWorker = null;
  5598. lWorker = aCommand._sender;
  5599. this.HandleKillCommand(lWorker,aCommand);
  5600. };
  5601. this.HandleRawCancelCommand = function (aCommand) {
  5602. var lWorker = null;
  5603. lWorker = aCommand._sender;
  5604. this.HandleCancelCommand(lWorker,aCommand);
  5605. };
  5606. this.HaveWebassembly = function () {
  5607. this.SendLoadCommands();
  5608. };
  5609. this.DoError = function (msg) {
  5610. this.DoLog("Error: " + msg);
  5611. };
  5612. this.AllocateNewWorker = function (aWorkerScript) {
  5613. var Result = null;
  5614. var lWorkerUrl = "";
  5615. this.DoLog("Allocating new worker for: " + aWorkerScript);
  5616. this.FWorkerCount += 1;
  5617. lWorkerUrl = aWorkerScript;
  5618. if (pas.System.Pos("?",lWorkerUrl) > 0) {
  5619. lWorkerUrl = lWorkerUrl + "&"}
  5620. else lWorkerUrl = lWorkerUrl + "?";
  5621. lWorkerUrl = lWorkerUrl + "worker=" + pas.SysUtils.IntToStr(this.FWorkerCount);
  5622. Result = $mod.TWasmThreadHelper.Create(lWorkerUrl);
  5623. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterWorker(Result,"threadworker" + pas.SysUtils.IntToStr(this.FWorkerCount));
  5624. if (this.FLogAPI$1) this.DoLog("Host not set, delaying sending load command to: " + aWorkerScript);
  5625. if (this.FOnAllocateWorker != null) this.FOnAllocateWorker(this,Result);
  5626. return Result;
  5627. };
  5628. this.SendLoadCommand = function (aThreadWorker) {
  5629. var WLC = null;
  5630. pas.System.Writeln("Sending load command to worker.");
  5631. WLC = pas["Rtl.WebThreads"].TWorkerLoadCommandHelper.Create(this.FModule,this.FMemory);
  5632. $mod.TWasmThreadHelper.SendCommand.call(aThreadWorker,WLC);
  5633. $mod.TWasmThreadHelper.SetWorkerState.call(aThreadWorker,2);
  5634. };
  5635. this.GetNewWorker = function () {
  5636. var Result = null;
  5637. var WT = null;
  5638. if (rtl.length(this.FIdleWorkers) === 0) {
  5639. if (this.FLogAPI$1) this.DoLog("No idle workers, creating new one");
  5640. if (rtl.length(this.FBusyWorkers) < this.FMaxWorkerCount) {
  5641. WT = this.AllocateNewWorker(this.FWorkerScript)}
  5642. else throw pas["Rtl.WebThreads"].EWasmThreads.$create("Create$1",[rtl.getResStr($mod,"SErrMaxWorkersReached")]);
  5643. } else {
  5644. WT = this.FIdleWorkers.pop();
  5645. };
  5646. this.FBusyWorkers.push(WT);
  5647. Result = WT;
  5648. return Result;
  5649. };
  5650. this.SpawnThread$1 = function (aInfo) {
  5651. var Result = 0;
  5652. var WT = null;
  5653. if (this.FWorkerCount === 0) this.AllocateInitialworkers();
  5654. this.DoLog$1("Enter SpawnThread for ID %d",pas.System.VarRecs(0,aInfo.ThreadID));
  5655. WT = this.GetNewWorker();
  5656. if (WT === null) {
  5657. this.DoError("Error: no worker !");
  5658. return -1;
  5659. };
  5660. $mod.TWasmThreadHelper.SetThreadInfo.call(WT,aInfo);
  5661. this.FThreads[aInfo.ThreadID] = WT;
  5662. this.SendRunCommand(WT);
  5663. Result = aInfo.ThreadID;
  5664. this.DoLog$1("Exit: SpawnThread for ID %d",pas.System.VarRecs(0,$mod.TWasmThreadHelper.GetThreadID.call(WT)));
  5665. return Result;
  5666. };
  5667. this.SendRunCommand = function (aThreadWorker) {
  5668. var WRC = null;
  5669. var $with = $mod.TWasmThreadHelper.GetThreadInfo.call(aThreadWorker);
  5670. WRC = pas["Rtl.WebThreads"].TWorkerRunCommandHelper.Create($with.ThreadID,$with.Arguments);
  5671. $mod.TWasmThreadHelper.SendCommand.call(aThreadWorker,WRC);
  5672. };
  5673. this.HandleSpawnCommand = function (aWorker, aCommand) {
  5674. var aInfo = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5675. aInfo.OriginThreadID = $mod.TWasmThreadHelper.GetThreadID.call(aWorker);
  5676. aInfo.ThreadID = aCommand.ThreadID;
  5677. aInfo.Arguments = aCommand.Arguments;
  5678. this.SpawnThread$1(pas["Rtl.WebThreads"].TThreadinfo.$clone(aInfo));
  5679. };
  5680. this.HandleReadyCommand = function (aWorker, aCommand) {
  5681. $mod.TWasmThreadHelper.SetWorkerState.call(aWorker,1);
  5682. if ((this.FMemory != null) && (this.FModule != null)) this.SendLoadCommand(aWorker);
  5683. };
  5684. this.HandleCancelCommand = function (aWorker, aCommand) {
  5685. if ((aWorker !== null) && (aCommand !== null)) ;
  5686. };
  5687. this.HandleCleanupCommand = function (aWorker, aCommand) {
  5688. var Idx = 0;
  5689. $mod.TWasmThreadHelper.SetThreadInfo.call(aWorker,pas["Rtl.WebThreads"].TThreadinfo.$new());
  5690. $mod.TWasmThreadHelper.SetWorkerState.call(aWorker,3);
  5691. Idx = this.FBusyWorkers.indexOf(aWorker);
  5692. if (Idx !== -1) this.FBusyWorkers.splice(Idx,1);
  5693. Idx = this.FIdleWorkers.indexOf(aWorker);
  5694. if (Idx === -1) this.FIdleWorkers = rtl.arrayPushN(this.FIdleWorkers,aWorker);
  5695. if (aCommand !== null) ;
  5696. };
  5697. this.HandleKillCommand = function (aWorker, aCommand) {
  5698. if ((aWorker !== null) && (aCommand !== null)) ;
  5699. };
  5700. this.HandleLoadedCommand = function (aWorker, aCommand) {
  5701. this.DoLog("Entering TThreadController.HandleLoadedCommand");
  5702. $mod.TWasmThreadHelper.SetWorkerState.call(aWorker,3);
  5703. if ($mod.TWasmThreadHelper.GetThreadID.call(aWorker) > 0) this.SendRunCommand(aWorker);
  5704. this.DoLog("Host: exiting TThreadController.HandleLoadedCommand");
  5705. if (aCommand !== null) ;
  5706. };
  5707. this.HandleConsoleCommand = function (aWorker, aCommand) {
  5708. var Prefix = "";
  5709. if (!this.FHandleConsoleMessages) return;
  5710. Prefix = aCommand.senderId;
  5711. if (Prefix === "") {
  5712. Prefix = pas.SysUtils.Format("[Wasm thread %d]: ",pas.System.VarRecs(0,$mod.TWasmThreadHelper.GetThreadID.call(aWorker)))}
  5713. else Prefix = "[" + Prefix + "]: ";
  5714. if (this.FOnConsoleWrite != null) {
  5715. this.FOnConsoleWrite(this,Prefix + aCommand.ConsoleMessage)}
  5716. else pas.System.Writeln(Prefix + aCommand.ConsoleMessage);
  5717. };
  5718. this.InitMessageCallBacks = function () {
  5719. var $with = pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance();
  5720. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdSpawn,rtl.createCallback(this,"HandleRawSpawnCommand"),false);
  5721. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdCleanup,rtl.createCallback(this,"HandleRawCleanupCommand"),false);
  5722. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdKill,rtl.createCallback(this,"HandleRawKillCommand"),false);
  5723. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdCancel,rtl.createCallback(this,"HandleRawCancelCommand"),false);
  5724. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdLoaded,rtl.createCallback(this,"HandleRawLoadedCommand"),false);
  5725. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdConsole,rtl.createCallback(this,"HandleRawConsoleCommand"),false);
  5726. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdReady,rtl.createCallback(this,"HandleRawReadyCommand"),false);
  5727. };
  5728. this.create$1 = function () {
  5729. this.Create$3(pas["Rtl.WebThreads"].DefaultThreadWorker,2);
  5730. return this;
  5731. };
  5732. this.Create$3 = function (aWorkerScript, aSpawnWorkerCount) {
  5733. pas["Rtl.WebThreads"].TWasmThreadController.create$1.call(this);
  5734. this.InitMessageCallBacks();
  5735. this.FThreads = new Object();
  5736. this.FWorkerScript = aWorkerScript;
  5737. this.FInitialWorkerCount = aSpawnWorkerCount;
  5738. this.FMaxWorkerCount = 100;
  5739. return this;
  5740. };
  5741. this.AllocateInitialworkers = function () {
  5742. var I = 0;
  5743. for (var $l = 1, $end = this.FInitialWorkerCount; $l <= $end; $l++) {
  5744. I = $l;
  5745. this.FIdleWorkers.push(this.AllocateNewWorker(this.FWorkerScript));
  5746. };
  5747. };
  5748. this.SpawnThread = function (start_arg) {
  5749. var Result = 0;
  5750. var aInfo = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5751. aInfo.ThreadID = start_arg;
  5752. aInfo.Arguments = start_arg;
  5753. aInfo.OriginThreadID = 0;
  5754. Result = this.SpawnThread$1(pas["Rtl.WebThreads"].TThreadinfo.$clone(aInfo));
  5755. return Result;
  5756. };
  5757. this.SendLoadCommands = function () {
  5758. var WT = null;
  5759. pas.System.Writeln("Send load commands");
  5760. this.DoLog("Sending load command to all workers");
  5761. for (var $in = this.FIdleWorkers, $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  5762. WT = $in[$l];
  5763. if ($mod.TWasmThreadHelper.GetWorkerState.call(WT) === 1) this.SendLoadCommand(WT);
  5764. };
  5765. };
  5766. });
  5767. this.globalThreadController = function () {
  5768. var Result = null;
  5769. Result = rtl.as(pas["Rtl.WebThreads"].TWasmThreadController.GetInstance(),$mod.TThreadController);
  5770. return Result;
  5771. };
  5772. $mod.$implcode = function () {
  5773. $mod.$resourcestrings = {SErrMaxWorkersReached: {org: "Cannot create thread worker, Maximum number of workers (%d) reached."}};
  5774. };
  5775. $mod.$init = function () {
  5776. pas["Rtl.WebThreads"].TWasmThreadController.SetInstanceClass($mod.TThreadController);
  5777. };
  5778. },[]);
  5779. rtl.module("CustApp",["System","Classes","SysUtils","Types","JS"],function () {
  5780. "use strict";
  5781. var $mod = this;
  5782. rtl.createClass(this,"TCustomApplication",pas.Classes.TComponent,function () {
  5783. this.$init = function () {
  5784. pas.Classes.TComponent.$init.call(this);
  5785. this.FExceptObjectJS = undefined;
  5786. this.FTerminated = false;
  5787. this.FOptionChar = "";
  5788. this.FCaseSensitiveOptions = false;
  5789. this.FStopOnException = false;
  5790. this.FExceptionExitCode = 0;
  5791. this.FExceptObject = null;
  5792. };
  5793. this.$final = function () {
  5794. this.FExceptObject = undefined;
  5795. pas.Classes.TComponent.$final.call(this);
  5796. };
  5797. this.GetEnvironmentVar = function (VarName) {
  5798. var Result = "";
  5799. Result = pas.SysUtils.GetEnvironmentVariable(VarName);
  5800. return Result;
  5801. };
  5802. this.Create$1 = function (AOwner) {
  5803. pas.Classes.TComponent.Create$1.call(this,AOwner);
  5804. this.FOptionChar = "-";
  5805. this.FCaseSensitiveOptions = true;
  5806. this.FStopOnException = false;
  5807. return this;
  5808. };
  5809. this.HandleException = function (Sender) {
  5810. var E = null;
  5811. var Tmp = null;
  5812. Tmp = null;
  5813. E = this.FExceptObject;
  5814. if ((E === null) && pas.System.Assigned(this.FExceptObjectJS)) {
  5815. if (rtl.isExt(this.FExceptObjectJS,Error,1)) {
  5816. Tmp = pas.SysUtils.EExternalException.$create("Create$1",[this.FExceptObjectJS.message])}
  5817. else if (rtl.isExt(this.FExceptObjectJS,Object,1) && this.FExceptObjectJS.hasOwnProperty("message")) {
  5818. Tmp = pas.SysUtils.EExternalException.$create("Create$1",["" + this.FExceptObjectJS["message"]])}
  5819. else Tmp = pas.SysUtils.EExternalException.$create("Create$1",[JSON.stringify(this.FExceptObjectJS)]);
  5820. E = Tmp;
  5821. };
  5822. try {
  5823. this.ShowException(E);
  5824. if (this.FStopOnException) this.Terminate$1(this.FExceptionExitCode);
  5825. } finally {
  5826. Tmp = rtl.freeLoc(Tmp);
  5827. };
  5828. if (Sender === null) ;
  5829. };
  5830. this.Run = function () {
  5831. do {
  5832. this.FExceptObject = null;
  5833. this.FExceptObjectJS = null;
  5834. try {
  5835. this.DoRun();
  5836. } catch ($e) {
  5837. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  5838. var E = $e;
  5839. this.FExceptObject = E;
  5840. this.FExceptObjectJS = E;
  5841. this.HandleException(this);
  5842. } else {
  5843. this.FExceptObject = null;
  5844. this.FExceptObjectJS = $e;
  5845. this.HandleException(this);
  5846. }
  5847. };
  5848. break;
  5849. } while (!this.FTerminated);
  5850. };
  5851. this.Terminate$1 = function (AExitCode) {
  5852. this.FTerminated = true;
  5853. rtl.exitcode = AExitCode;
  5854. };
  5855. });
  5856. });
  5857. rtl.module("webworkerbase",["System","JS","weborworker"],function () {
  5858. "use strict";
  5859. var $mod = this;
  5860. });
  5861. rtl.module("webworker",["System","JS","weborworker","webworkerbase"],function () {
  5862. "use strict";
  5863. var $mod = this;
  5864. });
  5865. rtl.module("workerapp",["System","Classes","SysUtils","CustApp","webworker","Rtl.WorkerCommands"],function () {
  5866. "use strict";
  5867. var $mod = this;
  5868. var $impl = $mod.$impl;
  5869. rtl.createClass(this,"TWorkerApplication",pas.CustApp.TCustomApplication,function () {
  5870. this.$init = function () {
  5871. pas.CustApp.TCustomApplication.$init.call(this);
  5872. this.FSendOutputToConsole = false;
  5873. };
  5874. this.Create$1 = function (AOwner) {
  5875. pas.CustApp.TCustomApplication.Create$1.call(this,AOwner);
  5876. this.FSendOutputToConsole = true;
  5877. return this;
  5878. };
  5879. this.ShowException = function (aError) {
  5880. var Ex = null;
  5881. Ex = pas["Rtl.WorkerCommands"].TWorkerExceptionCommandHelper.Create(aError.$classname,aError.fMessage,-1);
  5882. this.SendCommand(Ex);
  5883. };
  5884. this.SendCommand = function (aCommand) {
  5885. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(aCommand);
  5886. };
  5887. });
  5888. $mod.$implcode = function () {
  5889. $impl.EnvNames = null;
  5890. $impl.ReloadEnvironmentStrings = function () {
  5891. var I = 0;
  5892. var S = "";
  5893. var N = "";
  5894. var A = [];
  5895. var P = [];
  5896. if ($impl.EnvNames != null) pas.SysUtils.FreeAndNil({p: $impl, get: function () {
  5897. return this.p.EnvNames;
  5898. }, set: function (v) {
  5899. this.p.EnvNames = v;
  5900. }});
  5901. $impl.EnvNames = new Object();
  5902. S = self.location.search;
  5903. S = pas.System.Copy(S,2,S.length - 1);
  5904. A = S.split("&");
  5905. for (var $l = 0, $end = rtl.length(A) - 1; $l <= $end; $l++) {
  5906. I = $l;
  5907. P = A[I].split("=");
  5908. N = pas.SysUtils.LowerCase(decodeURIComponent(P[0]));
  5909. if (rtl.length(P) === 2) {
  5910. $impl.EnvNames[N] = decodeURIComponent(P[1])}
  5911. else if (rtl.length(P) === 1) $impl.EnvNames[N] = "";
  5912. };
  5913. };
  5914. $impl.MyGetEnvironmentVariable = function (EnvVar) {
  5915. var Result = "";
  5916. var aName = "";
  5917. aName = pas.SysUtils.LowerCase(EnvVar);
  5918. if ($impl.EnvNames.hasOwnProperty(aName)) {
  5919. Result = "" + $impl.EnvNames[aName]}
  5920. else Result = "";
  5921. return Result;
  5922. };
  5923. $impl.MyGetEnvironmentVariableCount = function () {
  5924. var Result = 0;
  5925. Result = rtl.length(Object.getOwnPropertyNames($impl.EnvNames));
  5926. return Result;
  5927. };
  5928. $impl.MyGetEnvironmentString = function (Index) {
  5929. var Result = "";
  5930. Result = "" + $impl.EnvNames[Object.getOwnPropertyNames($impl.EnvNames)[Index]];
  5931. return Result;
  5932. };
  5933. };
  5934. $mod.$init = function () {
  5935. $impl.ReloadEnvironmentStrings();
  5936. pas.SysUtils.OnGetEnvironmentVariable = $impl.MyGetEnvironmentVariable;
  5937. pas.SysUtils.OnGetEnvironmentVariableCount = $impl.MyGetEnvironmentVariableCount;
  5938. pas.SysUtils.OnGetEnvironmentString = $impl.MyGetEnvironmentString;
  5939. };
  5940. },["JS","Types"]);
  5941. rtl.module("wasiworkerapp",["System","Classes","SysUtils","workerapp","wasienv"],function () {
  5942. "use strict";
  5943. var $mod = this;
  5944. rtl.createClass(this,"TWorkerWASIHostApplication",pas.workerapp.TWorkerApplication,function () {
  5945. this._WasiHostClass = null;
  5946. this.$init = function () {
  5947. pas.workerapp.TWorkerApplication.$init.call(this);
  5948. this.FHost = null;
  5949. this.FOnHostCreated = null;
  5950. };
  5951. this.$final = function () {
  5952. this.FHost = undefined;
  5953. this.FOnHostCreated = undefined;
  5954. pas.workerapp.TWorkerApplication.$final.call(this);
  5955. };
  5956. this.GetEnv = function () {
  5957. var Result = null;
  5958. Result = this.FHost.GetEnv();
  5959. return Result;
  5960. };
  5961. this.RegisterMessageHandlers = function () {
  5962. };
  5963. this.DoRun = function () {
  5964. };
  5965. this.CreateHost = function () {
  5966. var Result = null;
  5967. var C = null;
  5968. C = this._WasiHostClass;
  5969. if (C === null) C = pas.wasienv.TWASIHost;
  5970. Result = C.$create("Create$1",[this]);
  5971. return Result;
  5972. };
  5973. this.DoHostCreated = function () {
  5974. if (this.FOnHostCreated != null) this.FOnHostCreated(this);
  5975. };
  5976. this.Create$1 = function (aOwner) {
  5977. pas.workerapp.TWorkerApplication.Create$1.call(this,aOwner);
  5978. this.RegisterMessageHandlers();
  5979. this.FHost = this.CreateHost();
  5980. this.DoHostCreated();
  5981. return this;
  5982. };
  5983. this.Destroy = function () {
  5984. pas.SysUtils.FreeAndNil({p: this, get: function () {
  5985. return this.p.FHost;
  5986. }, set: function (v) {
  5987. this.p.FHost = v;
  5988. }});
  5989. pas.Classes.TComponent.Destroy.call(this);
  5990. };
  5991. this.SetWasiHostClass = function (aClass) {
  5992. $mod.TWorkerWASIHostApplication._WasiHostClass = aClass;
  5993. };
  5994. this.StartWebAssembly = function (aPath, DoRun, aBeforeStart, aAfterStart) {
  5995. this.FHost.StartWebAssembly(aPath,DoRun,aBeforeStart,aAfterStart);
  5996. };
  5997. });
  5998. });
  5999. rtl.module("Rtl.workerthreadhost",["System","Types","Classes","SysUtils","JS","CustApp","webworker","webassembly","wasienv","Rtl.WebThreads","Rtl.threadcontroller","Rtl.WorkerCommands","wasiworkerapp"],function () {
  6000. "use strict";
  6001. var $mod = this;
  6002. rtl.createClass(this,"TWASIThreadControllerHost",pas.wasienv.TWASIHost,function () {
  6003. this.NeedSharedMemory = function () {
  6004. var Result = false;
  6005. Result = true;
  6006. return Result;
  6007. };
  6008. this.GetThreadSupport = function () {
  6009. var Result = null;
  6010. Result = rtl.as(pas["Rtl.WebThreads"].TWasmThreadController.GetInstance(),pas["Rtl.threadcontroller"].TThreadController);
  6011. return Result;
  6012. };
  6013. this.DoAfterInstantiate = function () {
  6014. pas.wasienv.TWASIHost.DoAfterInstantiate.call(this);
  6015. if (this.GetThreadSupport() != null) this.GetThreadSupport().SetWasmModuleAndMemory(this.FPreparedStartDescriptor.Module,this.FPreparedStartDescriptor.Memory);
  6016. };
  6017. this.CreateWasiEnvironment = function () {
  6018. var Result = null;
  6019. Result = pas.wasienv.TWASIHost.CreateWasiEnvironment.call(this);
  6020. return Result;
  6021. };
  6022. });
  6023. rtl.createClass(this,"TWorkerThreadControllerApplication",pas.wasiworkerapp.TWorkerWASIHostApplication,function () {
  6024. this.$init = function () {
  6025. pas.wasiworkerapp.TWorkerWASIHostApplication.$init.call(this);
  6026. this.FThreadSupport = null;
  6027. };
  6028. this.$final = function () {
  6029. this.FThreadSupport = undefined;
  6030. pas.wasiworkerapp.TWorkerWASIHostApplication.$final.call(this);
  6031. };
  6032. this.HandleRawExecuteCommand = function (aCommand) {
  6033. this.HandleExecuteCommand(aCommand);
  6034. };
  6035. this.HandleRawRpcCommand = function (aCommand) {
  6036. this.HandleRpcCommand(aCommand);
  6037. };
  6038. this.DoHostCreated = function () {
  6039. var Mem = pas.webassembly.TJSWebAssemblyMemoryDescriptor.$new();
  6040. pas.wasiworkerapp.TWorkerWASIHostApplication.DoHostCreated.call(this);
  6041. Mem.initial = 256;
  6042. Mem.maximum = 512;
  6043. Mem.shared = true;
  6044. this.FHost.FMemoryDescriptor.$assign(Mem);
  6045. };
  6046. this.RegisterMessageHandlers = function () {
  6047. pas.wasiworkerapp.TWorkerWASIHostApplication.RegisterMessageHandlers.call(this);
  6048. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterCommandHandler(pas["Rtl.WebThreads"].cmdExecute,rtl.createCallback(this,"HandleRawExecuteCommand"),false);
  6049. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterCommandHandler(pas["Rtl.WebThreads"].cmdRPC,rtl.createCallback(this,"HandleRawRpcCommand"),false);
  6050. };
  6051. this.HandleExecuteCommand = function (aCmd) {
  6052. var lName = "";
  6053. var lVal = undefined;
  6054. if (rtl.isObject(aCmd.Env)) {
  6055. this.GetEnv().FEnvironment.Clear();
  6056. for (var $in = Object.getOwnPropertyNames(aCmd.Env), $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  6057. lName = $in[$l];
  6058. lVal = aCmd.Env[lName];
  6059. if (rtl.isString(lVal)) this.GetEnv().FEnvironment.SetValue(lName,lVal);
  6060. };
  6061. };
  6062. if (rtl.isString(aCmd.ExecuteFunc)) this.FHost.FRunEntryFunction = aCmd.ExecuteFunc;
  6063. this.StartWebAssembly(aCmd.Url,true,null,null);
  6064. };
  6065. this.HandleRpcCommand = function (aCmd) {
  6066. var res = null;
  6067. var data = undefined;
  6068. var errClass = "";
  6069. var errMessage = "";
  6070. if (aCmd.id === "") {
  6071. res = pas["Rtl.WebThreads"].TWorkerRpcResultCommandHelper.CreateError(aCmd.id,-32600,"Invalid request: No json-rpc ID")}
  6072. else if (aCmd.jsonrpc !== "2.0") {
  6073. res = pas["Rtl.WebThreads"].TWorkerRpcResultCommandHelper.CreateError(aCmd.id,-32600,"Invalid request: no jsonrpc version")}
  6074. else if (!(this.FHost.FExported[aCmd.method] != null)) {
  6075. res = pas["Rtl.WebThreads"].TWorkerRpcResultCommandHelper.CreateError(aCmd.id,-32601,'Method "' + aCmd.method + '" not found')}
  6076. else {
  6077. try {
  6078. if (rtl.isArray(aCmd.params)) {
  6079. data = this.FHost.FExported[aCmd.method].apply(null,aCmd.params)}
  6080. else data = this.FHost.FExported[aCmd.method].call(null);
  6081. res = pas["Rtl.WebThreads"].TWorkerRpcResultCommandHelper.Create(aCmd.id,data);
  6082. } catch ($e) {
  6083. if (rtl.isExt($e,Error)) {
  6084. var JE = $e;
  6085. errClass = pas.JS.JSClassName(JE);
  6086. errMessage = JE.message;
  6087. } else if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  6088. var E = $e;
  6089. errClass = E.$classname;
  6090. errMessage = E.fMessage;
  6091. } else throw $e
  6092. };
  6093. if (!(res != null)) res = pas["Rtl.WebThreads"].TWorkerRpcResultCommandHelper.CreateError(aCmd.id,-32603,"Exception " + errClass + ' while executing "' + aCmd.method + '" : ' + errMessage);
  6094. };
  6095. self.postMessage(res);
  6096. };
  6097. this.Create$1 = function (aOwner) {
  6098. var lWorker = "";
  6099. pas.wasiworkerapp.TWorkerWASIHostApplication.Create$1.call(this,aOwner);
  6100. this.FThreadSupport = pas["Rtl.WebThreads"].TWasmThreadSupportApi.$create("Create$1",[this.GetEnv()]);
  6101. lWorker = this.GetEnvironmentVar("worker");
  6102. if (lWorker === "") lWorker = "worker";
  6103. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().FDefaultSenderID = lWorker;
  6104. pas["Rtl.threadcontroller"].globalThreadController().AllocateInitialworkers();
  6105. return this;
  6106. };
  6107. this.Destroy = function () {
  6108. pas.SysUtils.FreeAndNil({p: this, get: function () {
  6109. return this.p.FThreadSupport;
  6110. }, set: function (v) {
  6111. this.p.FThreadSupport = v;
  6112. }});
  6113. pas.wasiworkerapp.TWorkerWASIHostApplication.Destroy.call(this);
  6114. };
  6115. });
  6116. $mod.$init = function () {
  6117. pas["Rtl.WebThreads"].TWasmThreadController.SetInstanceClass(pas["Rtl.threadcontroller"].TThreadController);
  6118. pas.wasiworkerapp.TWorkerWASIHostApplication.SetWasiHostClass($mod.TWASIThreadControllerHost);
  6119. };
  6120. });
  6121. rtl.module("program",["System","Classes","Rtl.threadcontroller","Rtl.workerthreadhost"],function () {
  6122. "use strict";
  6123. var $mod = this;
  6124. rtl.createClass(this,"TApplication",pas["Rtl.workerthreadhost"].TWorkerThreadControllerApplication,function () {
  6125. });
  6126. this.App = null;
  6127. $mod.$main = function () {
  6128. pas["Rtl.threadcontroller"].globalThreadController().FHandleConsoleMessages = true;
  6129. $mod.App = $mod.TApplication.$create("Create$1",[null]);
  6130. $mod.App.Run();
  6131. };
  6132. });
  6133. rtl.run();
  6134. //# sourceMappingURL=wasmthreadcontroller.js.map