pas2jsthreadworker.js 214 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173
  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.HaveSharedArrayBuffer = function () {
  1687. return (typeof SharedArrayBuffer !== 'undefined');
  1688. };
  1689. this.SharedToNonShared = function (aBuffer) {
  1690. var Result = null;
  1691. var Src = null;
  1692. var Dest = null;
  1693. if ($mod.HaveSharedArrayBuffer() && rtl.isExt(aBuffer,SharedArrayBuffer)) {
  1694. Result = new ArrayBuffer(aBuffer.byteLength);
  1695. Src = new Uint8Array(aBuffer);
  1696. Dest = new Uint8Array(Result);
  1697. Dest.set(Src);
  1698. } else Result = aBuffer;
  1699. return Result;
  1700. };
  1701. this.SharedToNonShared$1 = function (aArray, aWordSized) {
  1702. var Result = null;
  1703. var Buf = null;
  1704. if ($mod.HaveSharedArrayBuffer() && rtl.isExt(aArray.buffer,SharedArrayBuffer)) {
  1705. Buf = aArray.buffer.slice(aArray.byteOffset,aArray.byteOffset + aArray.byteLength);
  1706. if (aWordSized) {
  1707. Result = new Uint16Array($mod.SharedToNonShared(Buf))}
  1708. else Result = new Uint8Array($mod.SharedToNonShared(Buf));
  1709. } else Result = aArray;
  1710. return Result;
  1711. };
  1712. });
  1713. rtl.module("SysUtils",["System","RTLConsts","JS"],function () {
  1714. "use strict";
  1715. var $mod = this;
  1716. var $impl = $mod.$impl;
  1717. this.FreeAndNil = function (Obj) {
  1718. var o = null;
  1719. o = Obj.get();
  1720. if (o === null) return;
  1721. Obj.set(null);
  1722. o.$destroy("Destroy");
  1723. };
  1724. rtl.recNewT(this,"TFormatSettings",function () {
  1725. this.CurrencyDecimals = 0;
  1726. this.CurrencyFormat = 0;
  1727. this.CurrencyString = "";
  1728. this.DateSeparator = "";
  1729. this.DecimalSeparator = "";
  1730. this.LongDateFormat = "";
  1731. this.LongTimeFormat = "";
  1732. this.NegCurrFormat = 0;
  1733. this.ShortDateFormat = "";
  1734. this.ShortTimeFormat = "";
  1735. this.ThousandSeparator = "";
  1736. this.TimeAMString = "";
  1737. this.TimePMString = "";
  1738. this.TimeSeparator = "";
  1739. this.TwoDigitYearCenturyWindow = 0;
  1740. this.InitLocaleHandler = null;
  1741. this.$new = function () {
  1742. var r = Object.create(this);
  1743. r.DateTimeToStrFormat = rtl.arraySetLength(null,"",2);
  1744. r.LongDayNames = rtl.arraySetLength(null,"",7);
  1745. r.LongMonthNames = rtl.arraySetLength(null,"",12);
  1746. r.ShortDayNames = rtl.arraySetLength(null,"",7);
  1747. r.ShortMonthNames = rtl.arraySetLength(null,"",12);
  1748. return r;
  1749. };
  1750. this.$eq = function (b) {
  1751. 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);
  1752. };
  1753. this.$assign = function (s) {
  1754. this.CurrencyDecimals = s.CurrencyDecimals;
  1755. this.CurrencyFormat = s.CurrencyFormat;
  1756. this.CurrencyString = s.CurrencyString;
  1757. this.DateSeparator = s.DateSeparator;
  1758. this.DateTimeToStrFormat = s.DateTimeToStrFormat.slice(0);
  1759. this.DecimalSeparator = s.DecimalSeparator;
  1760. this.LongDateFormat = s.LongDateFormat;
  1761. this.LongDayNames = s.LongDayNames.slice(0);
  1762. this.LongMonthNames = s.LongMonthNames.slice(0);
  1763. this.LongTimeFormat = s.LongTimeFormat;
  1764. this.NegCurrFormat = s.NegCurrFormat;
  1765. this.ShortDateFormat = s.ShortDateFormat;
  1766. this.ShortDayNames = s.ShortDayNames.slice(0);
  1767. this.ShortMonthNames = s.ShortMonthNames.slice(0);
  1768. this.ShortTimeFormat = s.ShortTimeFormat;
  1769. this.ThousandSeparator = s.ThousandSeparator;
  1770. this.TimeAMString = s.TimeAMString;
  1771. this.TimePMString = s.TimePMString;
  1772. this.TimeSeparator = s.TimeSeparator;
  1773. this.TwoDigitYearCenturyWindow = s.TwoDigitYearCenturyWindow;
  1774. return this;
  1775. };
  1776. this.GetJSLocale = function () {
  1777. return Intl.DateTimeFormat().resolvedOptions().locale;
  1778. };
  1779. this.Create = function () {
  1780. var Result = $mod.TFormatSettings.$new();
  1781. Result.$assign($mod.TFormatSettings.Create$1($mod.TFormatSettings.GetJSLocale()));
  1782. return Result;
  1783. };
  1784. this.Create$1 = function (ALocale) {
  1785. var Result = $mod.TFormatSettings.$new();
  1786. Result.LongDayNames = $impl.DefaultLongDayNames.slice(0);
  1787. Result.ShortDayNames = $impl.DefaultShortDayNames.slice(0);
  1788. Result.ShortMonthNames = $impl.DefaultShortMonthNames.slice(0);
  1789. Result.LongMonthNames = $impl.DefaultLongMonthNames.slice(0);
  1790. Result.DateTimeToStrFormat[0] = "c";
  1791. Result.DateTimeToStrFormat[1] = "f";
  1792. Result.DateSeparator = "-";
  1793. Result.TimeSeparator = ":";
  1794. Result.ShortDateFormat = "yyyy-mm-dd";
  1795. Result.LongDateFormat = "ddd, yyyy-mm-dd";
  1796. Result.ShortTimeFormat = "hh:nn";
  1797. Result.LongTimeFormat = "hh:nn:ss";
  1798. Result.DecimalSeparator = ".";
  1799. Result.ThousandSeparator = ",";
  1800. Result.TimeAMString = "AM";
  1801. Result.TimePMString = "PM";
  1802. Result.TwoDigitYearCenturyWindow = 50;
  1803. Result.CurrencyFormat = 0;
  1804. Result.NegCurrFormat = 0;
  1805. Result.CurrencyDecimals = 2;
  1806. Result.CurrencyString = "$";
  1807. if ($mod.TFormatSettings.InitLocaleHandler != null) $mod.TFormatSettings.InitLocaleHandler($mod.UpperCase(ALocale),$mod.TFormatSettings.$clone(Result));
  1808. return Result;
  1809. };
  1810. },true);
  1811. rtl.createClass(this,"Exception",pas.System.TObject,function () {
  1812. this.LogMessageOnCreate = false;
  1813. this.$init = function () {
  1814. pas.System.TObject.$init.call(this);
  1815. this.fMessage = "";
  1816. this.FJSError = null;
  1817. };
  1818. this.$final = function () {
  1819. this.FJSError = undefined;
  1820. pas.System.TObject.$final.call(this);
  1821. };
  1822. this.Create$1 = function (Msg) {
  1823. this.fMessage = Msg;
  1824. this.FJSError = new Error();
  1825. if (this.LogMessageOnCreate) pas.System.Writeln("Created exception ",this.$classname," with message: ",Msg);
  1826. return this;
  1827. };
  1828. this.CreateFmt = function (Msg, Args) {
  1829. this.Create$1($mod.Format(Msg,Args));
  1830. return this;
  1831. };
  1832. });
  1833. rtl.createClass(this,"EExternal",this.Exception,function () {
  1834. });
  1835. rtl.createClass(this,"EInvalidCast",this.Exception,function () {
  1836. });
  1837. rtl.createClass(this,"EConvertError",this.Exception,function () {
  1838. });
  1839. rtl.createClass(this,"EIntError",this.EExternal,function () {
  1840. });
  1841. rtl.createClass(this,"ERangeError",this.EIntError,function () {
  1842. });
  1843. rtl.createClass(this,"EExternalException",this.EExternal,function () {
  1844. });
  1845. rtl.createClass(this,"EAbstractError",this.Exception,function () {
  1846. });
  1847. this.TrimLeft = function (S) {
  1848. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'');
  1849. };
  1850. this.UpperCase = function (s) {
  1851. return s.toUpperCase();
  1852. };
  1853. this.LowerCase = function (s) {
  1854. return s.toLowerCase();
  1855. };
  1856. this.CompareStr = function (s1, s2) {
  1857. var l1 = s1.length;
  1858. var l2 = s2.length;
  1859. if (l1<=l2){
  1860. var s = s2.substr(0,l1);
  1861. if (s1<s){ return -1;
  1862. } else if (s1>s){ return 1;
  1863. } else { return l1<l2 ? -1 : 0; };
  1864. } else {
  1865. var s = s1.substr(0,l2);
  1866. if (s<s2){ return -1;
  1867. } else { return 1; };
  1868. };
  1869. };
  1870. this.CompareText = function (s1, s2) {
  1871. var l1 = s1.toLowerCase();
  1872. var l2 = s2.toLowerCase();
  1873. if (l1>l2){ return 1;
  1874. } else if (l1<l2){ return -1;
  1875. } else { return 0; };
  1876. };
  1877. this.Format = function (Fmt, Args) {
  1878. var Result = "";
  1879. Result = $mod.Format$1(Fmt,Args,$mod.FormatSettings);
  1880. return Result;
  1881. };
  1882. this.Format$1 = function (Fmt, Args, aSettings) {
  1883. var Result = "";
  1884. var ChPos = 0;
  1885. var OldPos = 0;
  1886. var ArgPos = 0;
  1887. var DoArg = 0;
  1888. var Len = 0;
  1889. var Hs = "";
  1890. var ToAdd = "";
  1891. var Index = 0;
  1892. var Width = 0;
  1893. var Prec = 0;
  1894. var Left = false;
  1895. var Fchar = "";
  1896. var vq = 0;
  1897. function ReadFormat() {
  1898. var Result = "";
  1899. var Value = 0;
  1900. function ReadInteger() {
  1901. var Code = 0;
  1902. var ArgN = 0;
  1903. if (Value !== -1) return;
  1904. OldPos = ChPos;
  1905. while ((ChPos <= Len) && (Fmt.charAt(ChPos - 1) <= "9") && (Fmt.charAt(ChPos - 1) >= "0")) ChPos += 1;
  1906. if (ChPos > Len) $impl.DoFormatError(1,Fmt);
  1907. if (Fmt.charAt(ChPos - 1) === "*") {
  1908. if (Index === 255) {
  1909. ArgN = ArgPos}
  1910. else {
  1911. ArgN = Index;
  1912. Index += 1;
  1913. };
  1914. if ((ChPos > OldPos) || (ArgN > (rtl.length(Args) - 1))) $impl.DoFormatError(1,Fmt);
  1915. ArgPos = ArgN + 1;
  1916. var $tmp = Args[ArgN].VType;
  1917. if ($tmp === 0) {
  1918. Value = Args[ArgN].VJSValue}
  1919. else if ($tmp === 19) {
  1920. Value = Args[ArgN].VJSValue}
  1921. else {
  1922. $impl.DoFormatError(1,Fmt);
  1923. };
  1924. ChPos += 1;
  1925. } else {
  1926. if (OldPos < ChPos) {
  1927. pas.System.val(pas.System.Copy(Fmt,OldPos,ChPos - OldPos),{get: function () {
  1928. return Value;
  1929. }, set: function (v) {
  1930. Value = v;
  1931. }},{get: function () {
  1932. return Code;
  1933. }, set: function (v) {
  1934. Code = v;
  1935. }});
  1936. if (Code > 0) $impl.DoFormatError(1,Fmt);
  1937. } else Value = -1;
  1938. };
  1939. };
  1940. function ReadIndex() {
  1941. if (Fmt.charAt(ChPos - 1) !== ":") {
  1942. ReadInteger()}
  1943. else Value = 0;
  1944. if (Fmt.charAt(ChPos - 1) === ":") {
  1945. if (Value === -1) $impl.DoFormatError(2,Fmt);
  1946. Index = Value;
  1947. Value = -1;
  1948. ChPos += 1;
  1949. };
  1950. };
  1951. function ReadLeft() {
  1952. if (Fmt.charAt(ChPos - 1) === "-") {
  1953. Left = true;
  1954. ChPos += 1;
  1955. } else Left = false;
  1956. };
  1957. function ReadWidth() {
  1958. ReadInteger();
  1959. if (Value !== -1) {
  1960. Width = Value;
  1961. Value = -1;
  1962. };
  1963. };
  1964. function ReadPrec() {
  1965. if (Fmt.charAt(ChPos - 1) === ".") {
  1966. ChPos += 1;
  1967. ReadInteger();
  1968. if (Value === -1) Value = 0;
  1969. Prec = Value;
  1970. };
  1971. };
  1972. Index = 255;
  1973. Width = -1;
  1974. Prec = -1;
  1975. Value = -1;
  1976. ChPos += 1;
  1977. if (Fmt.charAt(ChPos - 1) === "%") {
  1978. Result = "%";
  1979. return Result;
  1980. };
  1981. ReadIndex();
  1982. ReadLeft();
  1983. ReadWidth();
  1984. ReadPrec();
  1985. Result = pas.System.upcase(Fmt.charAt(ChPos - 1));
  1986. return Result;
  1987. };
  1988. function Checkarg(AT, err) {
  1989. var Result = false;
  1990. Result = false;
  1991. if (Index === 255) {
  1992. DoArg = ArgPos}
  1993. else DoArg = Index;
  1994. ArgPos = DoArg + 1;
  1995. if ((DoArg > (rtl.length(Args) - 1)) || (Args[DoArg].VType !== AT)) {
  1996. if (err) $impl.DoFormatError(3,Fmt);
  1997. ArgPos -= 1;
  1998. return Result;
  1999. };
  2000. Result = true;
  2001. return Result;
  2002. };
  2003. Result = "";
  2004. Len = Fmt.length;
  2005. ChPos = 1;
  2006. OldPos = 1;
  2007. ArgPos = 0;
  2008. while (ChPos <= Len) {
  2009. while ((ChPos <= Len) && (Fmt.charAt(ChPos - 1) !== "%")) ChPos += 1;
  2010. if (ChPos > OldPos) Result = Result + pas.System.Copy(Fmt,OldPos,ChPos - OldPos);
  2011. if (ChPos < Len) {
  2012. Fchar = ReadFormat();
  2013. var $tmp = Fchar;
  2014. if ($tmp === "D") {
  2015. if (Checkarg(0,false)) {
  2016. ToAdd = $mod.IntToStr(Args[DoArg].VJSValue)}
  2017. else if (Checkarg(19,true)) ToAdd = $mod.IntToStr(Args[DoArg].VJSValue);
  2018. Width = Math.abs(Width);
  2019. Index = Prec - ToAdd.length;
  2020. if (ToAdd.charAt(0) !== "-") {
  2021. ToAdd = pas.System.StringOfChar("0",Index) + ToAdd}
  2022. else pas.System.Insert(pas.System.StringOfChar("0",Index + 1),{get: function () {
  2023. return ToAdd;
  2024. }, set: function (v) {
  2025. ToAdd = v;
  2026. }},2);
  2027. } else if ($tmp === "U") {
  2028. if (Checkarg(0,false)) {
  2029. ToAdd = $mod.IntToStr(Args[DoArg].VJSValue >>> 0)}
  2030. else if (Checkarg(19,true)) ToAdd = $mod.IntToStr(Args[DoArg].VJSValue);
  2031. Width = Math.abs(Width);
  2032. Index = Prec - ToAdd.length;
  2033. ToAdd = pas.System.StringOfChar("0",Index) + ToAdd;
  2034. } else if ($tmp === "E") {
  2035. if (Checkarg(12,false)) {
  2036. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,2,3,Prec,aSettings)}
  2037. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,2,3,Prec,aSettings);
  2038. } else if ($tmp === "F") {
  2039. if (Checkarg(12,false)) {
  2040. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,0,9999,Prec,aSettings)}
  2041. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,0,9999,Prec,aSettings);
  2042. } else if ($tmp === "G") {
  2043. if (Checkarg(12,false)) {
  2044. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,1,Prec,3,aSettings)}
  2045. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,1,Prec,3,aSettings);
  2046. } else if ($tmp === "N") {
  2047. if (Checkarg(12,false)) {
  2048. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,3,9999,Prec,aSettings)}
  2049. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,3,9999,Prec,aSettings);
  2050. } else if ($tmp === "M") {
  2051. if (Checkarg(12,false)) {
  2052. ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue / 10000,4,9999,Prec,aSettings)}
  2053. else if (Checkarg(3,true)) ToAdd = $mod.FloatToStrF$1(Args[DoArg].VJSValue,4,9999,Prec,aSettings);
  2054. } else if ($tmp === "S") {
  2055. if (Checkarg(18,false)) {
  2056. Hs = Args[DoArg].VJSValue}
  2057. else if (Checkarg(9,true)) Hs = Args[DoArg].VJSValue;
  2058. Index = Hs.length;
  2059. if ((Prec !== -1) && (Index > Prec)) Index = Prec;
  2060. ToAdd = pas.System.Copy(Hs,1,Index);
  2061. } else if ($tmp === "P") {
  2062. if (Checkarg(0,false)) {
  2063. ToAdd = $mod.IntToHex(Args[DoArg].VJSValue,8)}
  2064. else if (Checkarg(0,true)) ToAdd = $mod.IntToHex(Args[DoArg].VJSValue,16);
  2065. } else if ($tmp === "X") {
  2066. if (Checkarg(0,false)) {
  2067. vq = Args[DoArg].VJSValue;
  2068. Index = 16;
  2069. } else if (Checkarg(19,true)) {
  2070. vq = Args[DoArg].VJSValue;
  2071. Index = 31;
  2072. };
  2073. if (Prec > Index) {
  2074. ToAdd = $mod.IntToHex(vq,Index)}
  2075. else {
  2076. Index = 1;
  2077. while ((rtl.shl(1,Index * 4) <= vq) && (Index < 16)) Index += 1;
  2078. if (Index > Prec) Prec = Index;
  2079. ToAdd = $mod.IntToHex(vq,Prec);
  2080. };
  2081. } else if ($tmp === "%") ToAdd = "%";
  2082. if (Width !== -1) if (ToAdd.length < Width) if (!Left) {
  2083. ToAdd = pas.System.StringOfChar(" ",Width - ToAdd.length) + ToAdd}
  2084. else ToAdd = ToAdd + pas.System.StringOfChar(" ",Width - ToAdd.length);
  2085. Result = Result + ToAdd;
  2086. };
  2087. ChPos += 1;
  2088. OldPos = ChPos;
  2089. };
  2090. return Result;
  2091. };
  2092. var Alpha = rtl.createSet(null,65,90,null,97,122,95);
  2093. var AlphaNum = rtl.unionSet(Alpha,rtl.createSet(null,48,57));
  2094. var Dot = ".";
  2095. this.IsValidIdent = function (Ident, AllowDots, StrictDots) {
  2096. var Result = false;
  2097. var First = false;
  2098. var I = 0;
  2099. var Len = 0;
  2100. Len = Ident.length;
  2101. if (Len < 1) return false;
  2102. First = true;
  2103. Result = false;
  2104. I = 1;
  2105. while (I <= Len) {
  2106. if (First) {
  2107. if (!(Ident.charCodeAt(I - 1) in Alpha)) return Result;
  2108. First = false;
  2109. } else if (AllowDots && (Ident.charAt(I - 1) === Dot)) {
  2110. if (StrictDots) {
  2111. if (I >= Len) return Result;
  2112. First = true;
  2113. };
  2114. } else if (!(Ident.charCodeAt(I - 1) in AlphaNum)) return Result;
  2115. I = I + 1;
  2116. };
  2117. Result = true;
  2118. return Result;
  2119. };
  2120. this.IntToStr = function (Value) {
  2121. var Result = "";
  2122. Result = "" + Value;
  2123. return Result;
  2124. };
  2125. this.TryStrToInt$2 = function (S, res) {
  2126. var Result = false;
  2127. Result = $impl.IntTryStrToInt(S,res,$mod.FormatSettings.DecimalSeparator);
  2128. return Result;
  2129. };
  2130. this.StrToInt = function (S) {
  2131. var Result = 0;
  2132. var R = 0;
  2133. if (!$mod.TryStrToInt$2(S,{get: function () {
  2134. return R;
  2135. }, set: function (v) {
  2136. R = v;
  2137. }})) throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SErrInvalidInteger"),pas.System.VarRecs(18,S)]);
  2138. Result = R;
  2139. return Result;
  2140. };
  2141. this.IntToHex = function (Value, Digits) {
  2142. var Result = "";
  2143. Result = "";
  2144. if (Value < 0) if (Value<0) Value = 0xFFFFFFFF + Value + 1;
  2145. Result=Value.toString(16);
  2146. Result = $mod.UpperCase(Result);
  2147. while (Result.length < Digits) Result = "0" + Result;
  2148. return Result;
  2149. };
  2150. this.TFloatFormat = {"0": "ffFixed", ffFixed: 0, "1": "ffGeneral", ffGeneral: 1, "2": "ffExponent", ffExponent: 2, "3": "ffNumber", ffNumber: 3, "4": "ffCurrency", ffCurrency: 4};
  2151. this.FloatToStrF$1 = function (Value, format, Precision, Digits, aSettings) {
  2152. var Result = "";
  2153. var TS = "";
  2154. var DS = "";
  2155. DS = aSettings.DecimalSeparator;
  2156. TS = aSettings.ThousandSeparator;
  2157. var $tmp = format;
  2158. if ($tmp === 1) {
  2159. Result = $impl.FormatGeneralFloat(Value,Precision,DS)}
  2160. else if ($tmp === 2) {
  2161. Result = $impl.FormatExponentFloat(Value,Precision,Digits,DS)}
  2162. else if ($tmp === 0) {
  2163. Result = $impl.FormatFixedFloat(Value,Digits,DS)}
  2164. else if ($tmp === 3) {
  2165. Result = $impl.FormatNumberFloat(Value,Digits,DS,TS)}
  2166. else if ($tmp === 4) Result = $impl.FormatNumberCurrency(Value * 10000,Digits,aSettings);
  2167. if ((format !== 4) && (Result.length > 1) && (Result.charAt(0) === "-")) $impl.RemoveLeadingNegativeSign({get: function () {
  2168. return Result;
  2169. }, set: function (v) {
  2170. Result = v;
  2171. }},DS,TS);
  2172. return Result;
  2173. };
  2174. this.OnGetEnvironmentVariable = null;
  2175. this.OnGetEnvironmentString = null;
  2176. this.OnGetEnvironmentVariableCount = null;
  2177. this.GetEnvironmentVariableCount = function () {
  2178. var Result = 0;
  2179. if ($mod.OnGetEnvironmentVariableCount != null) {
  2180. Result = $mod.OnGetEnvironmentVariableCount()}
  2181. else Result = 0;
  2182. return Result;
  2183. };
  2184. this.GetEnvironmentString = function (Index) {
  2185. var Result = "";
  2186. if ($mod.OnGetEnvironmentString != null) {
  2187. Result = $mod.OnGetEnvironmentString(Index)}
  2188. else Result = "";
  2189. return Result;
  2190. };
  2191. this.TimeSeparator = "";
  2192. this.DateSeparator = "";
  2193. this.ShortDateFormat = "";
  2194. this.LongDateFormat = "";
  2195. this.ShortTimeFormat = "";
  2196. this.LongTimeFormat = "";
  2197. this.DecimalSeparator = "";
  2198. this.ThousandSeparator = "";
  2199. this.TimeAMString = "";
  2200. this.TimePMString = "";
  2201. this.ShortMonthNames = rtl.arraySetLength(null,"",12);
  2202. this.LongMonthNames = rtl.arraySetLength(null,"",12);
  2203. this.ShortDayNames = rtl.arraySetLength(null,"",7);
  2204. this.LongDayNames = rtl.arraySetLength(null,"",7);
  2205. this.FormatSettings = this.TFormatSettings.$new();
  2206. this.CurrencyFormat = 0;
  2207. this.NegCurrFormat = 0;
  2208. this.CurrencyDecimals = 0;
  2209. this.CurrencyString = "";
  2210. $mod.$implcode = function () {
  2211. $impl.DefaultShortMonthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  2212. $impl.DefaultLongMonthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  2213. $impl.DefaultShortDayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  2214. $impl.DefaultLongDayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
  2215. $impl.feInvalidFormat = 1;
  2216. $impl.feMissingArgument = 2;
  2217. $impl.feInvalidArgIndex = 3;
  2218. $impl.DoFormatError = function (ErrCode, fmt) {
  2219. var $tmp = ErrCode;
  2220. if ($tmp === 1) {
  2221. throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SInvalidFormat"),pas.System.VarRecs(18,fmt)])}
  2222. else if ($tmp === 2) {
  2223. throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SArgumentMissing"),pas.System.VarRecs(18,fmt)])}
  2224. else if ($tmp === 3) throw $mod.EConvertError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SInvalidArgIndex"),pas.System.VarRecs(18,fmt)]);
  2225. };
  2226. $impl.maxdigits = 15;
  2227. $impl.ReplaceDecimalSep = function (S, DS) {
  2228. var Result = "";
  2229. var P = 0;
  2230. P = pas.System.Pos(".",S);
  2231. if (P > 0) {
  2232. Result = pas.System.Copy(S,1,P - 1) + DS + pas.System.Copy(S,P + 1,S.length - P)}
  2233. else Result = S;
  2234. return Result;
  2235. };
  2236. $impl.FormatGeneralFloat = function (Value, Precision, DS) {
  2237. var Result = "";
  2238. var P = 0;
  2239. var PE = 0;
  2240. var Q = 0;
  2241. var Exponent = 0;
  2242. if ((Precision === -1) || (Precision > 15)) Precision = 15;
  2243. Result = rtl.floatToStr(Value,Precision + 7);
  2244. Result = $mod.TrimLeft(Result);
  2245. P = pas.System.Pos(".",Result);
  2246. if (P === 0) return Result;
  2247. PE = pas.System.Pos("E",Result);
  2248. if (PE === 0) {
  2249. Result = $impl.ReplaceDecimalSep(Result,DS);
  2250. return Result;
  2251. };
  2252. Q = PE + 2;
  2253. Exponent = 0;
  2254. while (Q <= Result.length) {
  2255. Exponent = ((Exponent * 10) + Result.charCodeAt(Q - 1)) - 48;
  2256. Q += 1;
  2257. };
  2258. if (Result.charAt((PE + 1) - 1) === "-") Exponent = -Exponent;
  2259. if (((P + Exponent) < PE) && (Exponent > -6)) {
  2260. Result = rtl.strSetLength(Result,PE - 1);
  2261. if (Exponent >= 0) {
  2262. for (var $l = 0, $end = Exponent - 1; $l <= $end; $l++) {
  2263. Q = $l;
  2264. Result = rtl.setCharAt(Result,P - 1,Result.charAt((P + 1) - 1));
  2265. P += 1;
  2266. };
  2267. Result = rtl.setCharAt(Result,P - 1,".");
  2268. P = 1;
  2269. if (Result.charAt(P - 1) === "-") P += 1;
  2270. while ((Result.charAt(P - 1) === "0") && (P < Result.length) && (pas.System.Copy(Result,P + 1,DS.length) !== DS)) pas.System.Delete({get: function () {
  2271. return Result;
  2272. }, set: function (v) {
  2273. Result = v;
  2274. }},P,1);
  2275. } else {
  2276. pas.System.Insert(pas.System.Copy("00000",1,-Exponent),{get: function () {
  2277. return Result;
  2278. }, set: function (v) {
  2279. Result = v;
  2280. }},P - 1);
  2281. Result = rtl.setCharAt(Result,P - Exponent - 1,Result.charAt(P - Exponent - 1 - 1));
  2282. Result = rtl.setCharAt(Result,P - 1,".");
  2283. if (Exponent !== -1) Result = rtl.setCharAt(Result,P - Exponent - 1 - 1,"0");
  2284. };
  2285. Q = Result.length;
  2286. while ((Q > 0) && (Result.charAt(Q - 1) === "0")) Q -= 1;
  2287. if (Result.charAt(Q - 1) === ".") Q -= 1;
  2288. if ((Q === 0) || ((Q === 1) && (Result.charAt(0) === "-"))) {
  2289. Result = "0"}
  2290. else Result = rtl.strSetLength(Result,Q);
  2291. } else {
  2292. while (Result.charAt(PE - 1 - 1) === "0") {
  2293. pas.System.Delete({get: function () {
  2294. return Result;
  2295. }, set: function (v) {
  2296. Result = v;
  2297. }},PE - 1,1);
  2298. PE -= 1;
  2299. };
  2300. if (Result.charAt(PE - 1 - 1) === DS) {
  2301. pas.System.Delete({get: function () {
  2302. return Result;
  2303. }, set: function (v) {
  2304. Result = v;
  2305. }},PE - 1,1);
  2306. PE -= 1;
  2307. };
  2308. if (Result.charAt((PE + 1) - 1) === "+") {
  2309. pas.System.Delete({get: function () {
  2310. return Result;
  2311. }, set: function (v) {
  2312. Result = v;
  2313. }},PE + 1,1)}
  2314. else PE += 1;
  2315. while (Result.charAt((PE + 1) - 1) === "0") pas.System.Delete({get: function () {
  2316. return Result;
  2317. }, set: function (v) {
  2318. Result = v;
  2319. }},PE + 1,1);
  2320. };
  2321. Result = $impl.ReplaceDecimalSep(Result,DS);
  2322. return Result;
  2323. };
  2324. $impl.FormatExponentFloat = function (Value, Precision, Digits, DS) {
  2325. var Result = "";
  2326. var P = 0;
  2327. DS = $mod.FormatSettings.DecimalSeparator;
  2328. if ((Precision === -1) || (Precision > 15)) Precision = 15;
  2329. Result = rtl.floatToStr(Value,Precision + 7);
  2330. while (Result.charAt(0) === " ") pas.System.Delete({get: function () {
  2331. return Result;
  2332. }, set: function (v) {
  2333. Result = v;
  2334. }},1,1);
  2335. P = pas.System.Pos("E",Result);
  2336. if (P === 0) {
  2337. Result = $impl.ReplaceDecimalSep(Result,DS);
  2338. return Result;
  2339. };
  2340. P += 2;
  2341. if (Digits > 4) Digits = 4;
  2342. Digits = (Result.length - P - Digits) + 1;
  2343. if (Digits < 0) {
  2344. pas.System.Insert(pas.System.Copy("0000",1,-Digits),{get: function () {
  2345. return Result;
  2346. }, set: function (v) {
  2347. Result = v;
  2348. }},P)}
  2349. else while ((Digits > 0) && (Result.charAt(P - 1) === "0")) {
  2350. pas.System.Delete({get: function () {
  2351. return Result;
  2352. }, set: function (v) {
  2353. Result = v;
  2354. }},P,1);
  2355. if (P > Result.length) {
  2356. pas.System.Delete({get: function () {
  2357. return Result;
  2358. }, set: function (v) {
  2359. Result = v;
  2360. }},P - 2,2);
  2361. break;
  2362. };
  2363. Digits -= 1;
  2364. };
  2365. Result = $impl.ReplaceDecimalSep(Result,DS);
  2366. return Result;
  2367. };
  2368. $impl.FormatFixedFloat = function (Value, Digits, DS) {
  2369. var Result = "";
  2370. if (Digits === -1) {
  2371. Digits = 2}
  2372. else if (Digits > 18) Digits = 18;
  2373. Result = rtl.floatToStr(Value,0,Digits);
  2374. if ((Result !== "") && (Result.charAt(0) === " ")) pas.System.Delete({get: function () {
  2375. return Result;
  2376. }, set: function (v) {
  2377. Result = v;
  2378. }},1,1);
  2379. Result = $impl.ReplaceDecimalSep(Result,DS);
  2380. return Result;
  2381. };
  2382. $impl.FormatNumberFloat = function (Value, Digits, DS, TS) {
  2383. var Result = "";
  2384. var P = 0;
  2385. if (Digits === -1) {
  2386. Digits = 2}
  2387. else if (Digits > 15) Digits = 15;
  2388. Result = rtl.floatToStr(Value,0,Digits);
  2389. if ((Result !== "") && (Result.charAt(0) === " ")) pas.System.Delete({get: function () {
  2390. return Result;
  2391. }, set: function (v) {
  2392. Result = v;
  2393. }},1,1);
  2394. P = pas.System.Pos(".",Result);
  2395. if (P <= 0) P = Result.length + 1;
  2396. Result = $impl.ReplaceDecimalSep(Result,DS);
  2397. P -= 3;
  2398. if ((TS !== "") && (TS !== "\x00")) while (P > 1) {
  2399. if (Result.charAt(P - 1 - 1) !== "-") pas.System.Insert(TS,{get: function () {
  2400. return Result;
  2401. }, set: function (v) {
  2402. Result = v;
  2403. }},P);
  2404. P -= 3;
  2405. };
  2406. return Result;
  2407. };
  2408. $impl.RemoveLeadingNegativeSign = function (AValue, DS, aThousandSeparator) {
  2409. var Result = false;
  2410. var i = 0;
  2411. var TS = "";
  2412. var StartPos = 0;
  2413. Result = false;
  2414. StartPos = 2;
  2415. TS = aThousandSeparator;
  2416. for (var $l = StartPos, $end = AValue.get().length; $l <= $end; $l++) {
  2417. i = $l;
  2418. Result = (AValue.get().charCodeAt(i - 1) in rtl.createSet(48,DS.charCodeAt(),69,43)) || (AValue.get().charAt(i - 1) === TS);
  2419. if (!Result) break;
  2420. };
  2421. if (Result && (AValue.get().charAt(0) === "-")) pas.System.Delete(AValue,1,1);
  2422. return Result;
  2423. };
  2424. $impl.FormatNumberCurrency = function (Value, Digits, aSettings) {
  2425. var Result = "";
  2426. var Negative = false;
  2427. var P = 0;
  2428. var CS = "";
  2429. var DS = "";
  2430. var TS = "";
  2431. DS = aSettings.DecimalSeparator;
  2432. TS = aSettings.ThousandSeparator;
  2433. CS = aSettings.CurrencyString;
  2434. if (Digits === -1) {
  2435. Digits = aSettings.CurrencyDecimals}
  2436. else if (Digits > 18) Digits = 18;
  2437. Result = rtl.floatToStr(Value / 10000,0,Digits);
  2438. Negative = Result.charAt(0) === "-";
  2439. if (Negative) pas.System.Delete({get: function () {
  2440. return Result;
  2441. }, set: function (v) {
  2442. Result = v;
  2443. }},1,1);
  2444. P = pas.System.Pos(".",Result);
  2445. if (TS !== "") {
  2446. if (P !== 0) {
  2447. Result = $impl.ReplaceDecimalSep(Result,DS)}
  2448. else P = Result.length + 1;
  2449. P -= 3;
  2450. while (P > 1) {
  2451. pas.System.Insert(TS,{get: function () {
  2452. return Result;
  2453. }, set: function (v) {
  2454. Result = v;
  2455. }},P);
  2456. P -= 3;
  2457. };
  2458. };
  2459. if (Negative) $impl.RemoveLeadingNegativeSign({get: function () {
  2460. return Result;
  2461. }, set: function (v) {
  2462. Result = v;
  2463. }},DS,TS);
  2464. if (!Negative) {
  2465. var $tmp = aSettings.CurrencyFormat;
  2466. if ($tmp === 0) {
  2467. Result = CS + Result}
  2468. else if ($tmp === 1) {
  2469. Result = Result + CS}
  2470. else if ($tmp === 2) {
  2471. Result = CS + " " + Result}
  2472. else if ($tmp === 3) Result = Result + " " + CS;
  2473. } else {
  2474. var $tmp1 = aSettings.NegCurrFormat;
  2475. if ($tmp1 === 0) {
  2476. Result = "(" + CS + Result + ")"}
  2477. else if ($tmp1 === 1) {
  2478. Result = "-" + CS + Result}
  2479. else if ($tmp1 === 2) {
  2480. Result = CS + "-" + Result}
  2481. else if ($tmp1 === 3) {
  2482. Result = CS + Result + "-"}
  2483. else if ($tmp1 === 4) {
  2484. Result = "(" + Result + CS + ")"}
  2485. else if ($tmp1 === 5) {
  2486. Result = "-" + Result + CS}
  2487. else if ($tmp1 === 6) {
  2488. Result = Result + "-" + CS}
  2489. else if ($tmp1 === 7) {
  2490. Result = Result + CS + "-"}
  2491. else if ($tmp1 === 8) {
  2492. Result = "-" + Result + " " + CS}
  2493. else if ($tmp1 === 9) {
  2494. Result = "-" + CS + " " + Result}
  2495. else if ($tmp1 === 10) {
  2496. Result = Result + " " + CS + "-"}
  2497. else if ($tmp1 === 11) {
  2498. Result = CS + " " + Result + "-"}
  2499. else if ($tmp1 === 12) {
  2500. Result = CS + " " + "-" + Result}
  2501. else if ($tmp1 === 13) {
  2502. Result = Result + "-" + " " + CS}
  2503. else if ($tmp1 === 14) {
  2504. Result = "(" + CS + " " + Result + ")"}
  2505. else if ($tmp1 === 15) Result = "(" + Result + " " + CS + ")";
  2506. };
  2507. return Result;
  2508. };
  2509. $impl.IntTryStrToInt = function (S, res, aSep) {
  2510. var Result = false;
  2511. var Radix = 10;
  2512. var N = "";
  2513. var J = undefined;
  2514. N = S;
  2515. if ((pas.System.Pos(aSep,N) !== 0) || (pas.System.Pos(".",N) !== 0)) return false;
  2516. var $tmp = pas.System.Copy(N,1,1);
  2517. if ($tmp === "$") {
  2518. Radix = 16}
  2519. else if ($tmp === "&") {
  2520. Radix = 8}
  2521. else if ($tmp === "%") Radix = 2;
  2522. if ((Radix !== 16) && (pas.System.Pos("e",$mod.LowerCase(N)) !== 0)) return false;
  2523. if (Radix !== 10) pas.System.Delete({get: function () {
  2524. return N;
  2525. }, set: function (v) {
  2526. N = v;
  2527. }},1,1);
  2528. J = parseInt(N,Radix);
  2529. Result = !isNaN(J);
  2530. if (Result) res.set(rtl.trunc(J));
  2531. return Result;
  2532. };
  2533. $impl.InitGlobalFormatSettings = function () {
  2534. $mod.FormatSettings.$assign($mod.TFormatSettings.Create());
  2535. $mod.TimeSeparator = $mod.FormatSettings.TimeSeparator;
  2536. $mod.DateSeparator = $mod.FormatSettings.DateSeparator;
  2537. $mod.ShortDateFormat = $mod.FormatSettings.ShortDateFormat;
  2538. $mod.LongDateFormat = $mod.FormatSettings.LongDateFormat;
  2539. $mod.ShortTimeFormat = $mod.FormatSettings.ShortTimeFormat;
  2540. $mod.LongTimeFormat = $mod.FormatSettings.LongTimeFormat;
  2541. $mod.DecimalSeparator = $mod.FormatSettings.DecimalSeparator;
  2542. $mod.ThousandSeparator = $mod.FormatSettings.ThousandSeparator;
  2543. $mod.TimeAMString = $mod.FormatSettings.TimeAMString;
  2544. $mod.TimePMString = $mod.FormatSettings.TimePMString;
  2545. $mod.CurrencyFormat = $mod.FormatSettings.CurrencyFormat;
  2546. $mod.NegCurrFormat = $mod.FormatSettings.NegCurrFormat;
  2547. $mod.CurrencyDecimals = $mod.FormatSettings.CurrencyDecimals;
  2548. $mod.CurrencyString = $mod.FormatSettings.CurrencyString;
  2549. };
  2550. $impl.DoClassRef = function (C) {
  2551. if (C === null) ;
  2552. };
  2553. };
  2554. $mod.$init = function () {
  2555. (function () {
  2556. $impl.InitGlobalFormatSettings();
  2557. })();
  2558. $impl.DoClassRef($mod.EInvalidCast);
  2559. $impl.DoClassRef($mod.EAbstractError);
  2560. $impl.DoClassRef($mod.ERangeError);
  2561. $mod.ShortMonthNames = $impl.DefaultShortMonthNames.slice(0);
  2562. $mod.LongMonthNames = $impl.DefaultLongMonthNames.slice(0);
  2563. $mod.ShortDayNames = $impl.DefaultShortDayNames.slice(0);
  2564. $mod.LongDayNames = $impl.DefaultLongDayNames.slice(0);
  2565. };
  2566. },[]);
  2567. rtl.module("Classes",["System","RTLConsts","Types","SysUtils","JS"],function () {
  2568. "use strict";
  2569. var $mod = this;
  2570. var $impl = $mod.$impl;
  2571. rtl.createClass(this,"EListError",pas.SysUtils.Exception,function () {
  2572. });
  2573. rtl.createClass(this,"EStringListError",this.EListError,function () {
  2574. });
  2575. rtl.createClass(this,"EComponentError",pas.SysUtils.Exception,function () {
  2576. });
  2577. rtl.createClass(this,"TFPList",pas.System.TObject,function () {
  2578. this.$init = function () {
  2579. pas.System.TObject.$init.call(this);
  2580. this.FList = [];
  2581. this.FCount = 0;
  2582. this.FCapacity = 0;
  2583. };
  2584. this.$final = function () {
  2585. this.FList = undefined;
  2586. pas.System.TObject.$final.call(this);
  2587. };
  2588. this.Get = function (Index) {
  2589. var Result = undefined;
  2590. if ((Index < 0) || (Index >= this.FCount)) this.RaiseIndexError(Index);
  2591. Result = this.FList[Index];
  2592. return Result;
  2593. };
  2594. this.SetCapacity = function (NewCapacity) {
  2595. if (NewCapacity < this.FCount) this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListCapacityError"),"" + NewCapacity);
  2596. if (NewCapacity === this.FCapacity) return;
  2597. this.FList = rtl.arraySetLength(this.FList,undefined,NewCapacity);
  2598. this.FCapacity = NewCapacity;
  2599. };
  2600. this.SetCount = function (NewCount) {
  2601. if (NewCount < 0) this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListCountError"),"" + NewCount);
  2602. if (NewCount > this.FCount) {
  2603. if (NewCount > this.FCapacity) this.SetCapacity(NewCount);
  2604. };
  2605. this.FCount = NewCount;
  2606. };
  2607. this.RaiseIndexError = function (Index) {
  2608. this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),"" + Index);
  2609. };
  2610. this.Destroy = function () {
  2611. this.Clear();
  2612. pas.System.TObject.Destroy.call(this);
  2613. };
  2614. this.Add = function (Item) {
  2615. var Result = 0;
  2616. if (this.FCount === this.FCapacity) this.Expand();
  2617. this.FList[this.FCount] = Item;
  2618. Result = this.FCount;
  2619. this.FCount += 1;
  2620. return Result;
  2621. };
  2622. this.Clear = function () {
  2623. if (rtl.length(this.FList) > 0) {
  2624. this.SetCount(0);
  2625. this.SetCapacity(0);
  2626. };
  2627. };
  2628. this.Delete = function (Index) {
  2629. if ((Index < 0) || (Index >= this.FCount)) this.$class.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),"" + Index);
  2630. this.FCount = this.FCount - 1;
  2631. this.FList.splice(Index,1);
  2632. this.FCapacity -= 1;
  2633. };
  2634. this.Error = function (Msg, Data) {
  2635. throw $mod.EListError.$create("CreateFmt",[Msg,pas.System.VarRecs(18,Data)]);
  2636. };
  2637. this.Expand = function () {
  2638. var Result = null;
  2639. var IncSize = 0;
  2640. if (this.FCount < this.FCapacity) return this;
  2641. IncSize = 4;
  2642. if (this.FCapacity > 3) IncSize = IncSize + 4;
  2643. if (this.FCapacity > 8) IncSize = IncSize + 8;
  2644. if (this.FCapacity > 127) IncSize += this.FCapacity >>> 2;
  2645. this.SetCapacity(this.FCapacity + IncSize);
  2646. Result = this;
  2647. return Result;
  2648. };
  2649. this.IndexOf = function (Item) {
  2650. var Result = 0;
  2651. var C = 0;
  2652. Result = 0;
  2653. C = this.FCount;
  2654. while ((Result < C) && (this.FList[Result] != Item)) Result += 1;
  2655. if (Result >= C) Result = -1;
  2656. return Result;
  2657. };
  2658. this.Last = function () {
  2659. var Result = undefined;
  2660. if (this.FCount === 0) {
  2661. Result = null}
  2662. else Result = this.Get(this.FCount - 1);
  2663. return Result;
  2664. };
  2665. this.Remove = function (Item) {
  2666. var Result = 0;
  2667. Result = this.IndexOf(Item);
  2668. if (Result !== -1) this.Delete(Result);
  2669. return Result;
  2670. };
  2671. });
  2672. rtl.createClass(this,"TPersistent",pas.System.TObject,function () {
  2673. });
  2674. rtl.createClass(this,"TStrings",this.TPersistent,function () {
  2675. this.$init = function () {
  2676. $mod.TPersistent.$init.call(this);
  2677. this.FSpecialCharsInited = false;
  2678. this.FAlwaysQuote = false;
  2679. this.FQuoteChar = "";
  2680. this.FDelimiter = "";
  2681. this.FNameValueSeparator = "";
  2682. this.FUpdateCount = 0;
  2683. this.FLBS = 0;
  2684. this.FSkipLastLineBreak = false;
  2685. this.FLineBreak = "";
  2686. };
  2687. this.GetSkipLastLineBreak = function () {
  2688. var Result = false;
  2689. this.CheckSpecialChars();
  2690. Result = this.FSkipLastLineBreak;
  2691. return Result;
  2692. };
  2693. this.Error = function (Msg, Data) {
  2694. throw $mod.EStringListError.$create("CreateFmt",[Msg,pas.System.VarRecs(18,pas.SysUtils.IntToStr(Data))]);
  2695. };
  2696. this.GetCapacity = function () {
  2697. var Result = 0;
  2698. Result = this.GetCount();
  2699. return Result;
  2700. };
  2701. this.GetTextStr = function () {
  2702. var Result = "";
  2703. var I = 0;
  2704. var S = "";
  2705. var NL = "";
  2706. this.CheckSpecialChars();
  2707. if (this.FLineBreak !== pas.System.sLineBreak) {
  2708. NL = this.FLineBreak}
  2709. else {
  2710. var $tmp = this.FLBS;
  2711. if ($tmp === 0) {
  2712. NL = "\n"}
  2713. else if ($tmp === 1) {
  2714. NL = "\r\n"}
  2715. else if ($tmp === 2) NL = "\r";
  2716. };
  2717. Result = "";
  2718. for (var $l = 0, $end = this.GetCount() - 1; $l <= $end; $l++) {
  2719. I = $l;
  2720. S = this.Get(I);
  2721. Result = Result + S;
  2722. if ((I < (this.GetCount() - 1)) || !this.GetSkipLastLineBreak()) Result = Result + NL;
  2723. };
  2724. return Result;
  2725. };
  2726. this.DoCompareText = function (s1, s2) {
  2727. var Result = 0;
  2728. Result = pas.SysUtils.CompareText(s1,s2);
  2729. return Result;
  2730. };
  2731. this.CheckSpecialChars = function () {
  2732. if (!this.FSpecialCharsInited) {
  2733. this.FQuoteChar = '"';
  2734. this.FDelimiter = ",";
  2735. this.FNameValueSeparator = "=";
  2736. this.FLBS = pas.System.DefaultTextLineBreakStyle;
  2737. this.FSpecialCharsInited = true;
  2738. this.FLineBreak = pas.System.sLineBreak;
  2739. };
  2740. };
  2741. this.Create$1 = function () {
  2742. pas.System.TObject.Create.call(this);
  2743. this.FAlwaysQuote = false;
  2744. return this;
  2745. };
  2746. this.Destroy = function () {
  2747. pas.System.TObject.Destroy.call(this);
  2748. };
  2749. this.Add = function (S) {
  2750. var Result = 0;
  2751. Result = this.GetCount();
  2752. this.Insert(this.GetCount(),S);
  2753. return Result;
  2754. };
  2755. this.IndexOf = function (S) {
  2756. var Result = 0;
  2757. Result = 0;
  2758. while ((Result < this.GetCount()) && (this.DoCompareText(this.Get(Result),S) !== 0)) Result = Result + 1;
  2759. if (Result === this.GetCount()) Result = -1;
  2760. return Result;
  2761. };
  2762. });
  2763. rtl.recNewT(this,"TStringItem",function () {
  2764. this.FString = "";
  2765. this.FObject = null;
  2766. this.$eq = function (b) {
  2767. return (this.FString === b.FString) && (this.FObject === b.FObject);
  2768. };
  2769. this.$assign = function (s) {
  2770. this.FString = s.FString;
  2771. this.FObject = s.FObject;
  2772. return this;
  2773. };
  2774. });
  2775. this.TStringsSortStyle = {"0": "sslNone", sslNone: 0, "1": "sslUser", sslUser: 1, "2": "sslAuto", sslAuto: 2};
  2776. rtl.createClass(this,"TStringList",this.TStrings,function () {
  2777. this.$init = function () {
  2778. $mod.TStrings.$init.call(this);
  2779. this.FList = [];
  2780. this.FCount = 0;
  2781. this.FOnChange = null;
  2782. this.FOnChanging = null;
  2783. this.FDuplicates = 0;
  2784. this.FCaseSensitive = false;
  2785. this.FOwnsObjects = false;
  2786. this.FSortStyle = 0;
  2787. };
  2788. this.$final = function () {
  2789. this.FList = undefined;
  2790. this.FOnChange = undefined;
  2791. this.FOnChanging = undefined;
  2792. $mod.TStrings.$final.call(this);
  2793. };
  2794. this.GetSorted = function () {
  2795. var Result = false;
  2796. Result = this.FSortStyle in rtl.createSet(1,2);
  2797. return Result;
  2798. };
  2799. this.Grow = function () {
  2800. var NC = 0;
  2801. NC = this.GetCapacity();
  2802. if (NC >= 256) {
  2803. NC = NC + rtl.trunc(NC / 4)}
  2804. else if (NC === 0) {
  2805. NC = 4}
  2806. else NC = NC * 4;
  2807. this.SetCapacity(NC);
  2808. };
  2809. this.InternalClear = function (FromIndex, ClearOnly) {
  2810. var I = 0;
  2811. if (FromIndex < this.FCount) {
  2812. if (this.FOwnsObjects) {
  2813. for (var $l = FromIndex, $end = this.FCount - 1; $l <= $end; $l++) {
  2814. I = $l;
  2815. this.FList[I].FString = "";
  2816. pas.SysUtils.FreeAndNil({p: this.FList[I], get: function () {
  2817. return this.p.FObject;
  2818. }, set: function (v) {
  2819. this.p.FObject = v;
  2820. }});
  2821. };
  2822. } else {
  2823. for (var $l1 = FromIndex, $end1 = this.FCount - 1; $l1 <= $end1; $l1++) {
  2824. I = $l1;
  2825. this.FList[I].FString = "";
  2826. };
  2827. };
  2828. this.FCount = FromIndex;
  2829. };
  2830. if (!ClearOnly) this.SetCapacity(0);
  2831. };
  2832. this.CheckIndex = function (AIndex) {
  2833. if ((AIndex < 0) || (AIndex >= this.FCount)) this.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),AIndex);
  2834. };
  2835. this.Changed = function () {
  2836. if (this.FUpdateCount === 0) {
  2837. if (this.FOnChange != null) this.FOnChange(this);
  2838. };
  2839. };
  2840. this.Changing = function () {
  2841. if (this.FUpdateCount === 0) if (this.FOnChanging != null) this.FOnChanging(this);
  2842. };
  2843. this.Get = function (Index) {
  2844. var Result = "";
  2845. this.CheckIndex(Index);
  2846. Result = this.FList[Index].FString;
  2847. return Result;
  2848. };
  2849. this.GetCapacity = function () {
  2850. var Result = 0;
  2851. Result = rtl.length(this.FList);
  2852. return Result;
  2853. };
  2854. this.GetCount = function () {
  2855. var Result = 0;
  2856. Result = this.FCount;
  2857. return Result;
  2858. };
  2859. this.SetCapacity = function (NewCapacity) {
  2860. if (NewCapacity < 0) this.Error(rtl.getResStr(pas.RTLConsts,"SListCapacityError"),NewCapacity);
  2861. if (NewCapacity !== this.GetCapacity()) this.FList = rtl.arraySetLength(this.FList,$mod.TStringItem,NewCapacity);
  2862. };
  2863. this.InsertItem = function (Index, S) {
  2864. this.InsertItem$1(Index,S,null);
  2865. };
  2866. this.InsertItem$1 = function (Index, S, O) {
  2867. var It = $mod.TStringItem.$new();
  2868. this.Changing();
  2869. if (this.FCount === this.GetCapacity()) this.Grow();
  2870. It.FString = S;
  2871. It.FObject = O;
  2872. this.FList.splice(Index,0,It);
  2873. this.FCount += 1;
  2874. this.Changed();
  2875. };
  2876. this.DoCompareText = function (s1, s2) {
  2877. var Result = 0;
  2878. if (this.FCaseSensitive) {
  2879. Result = pas.SysUtils.CompareStr(s1,s2)}
  2880. else Result = pas.SysUtils.CompareText(s1,s2);
  2881. return Result;
  2882. };
  2883. this.Destroy = function () {
  2884. this.InternalClear(0,false);
  2885. $mod.TStrings.Destroy.call(this);
  2886. };
  2887. this.Add = function (S) {
  2888. var Result = 0;
  2889. if (!(this.FSortStyle === 2)) {
  2890. Result = this.FCount}
  2891. else if (this.Find(S,{get: function () {
  2892. return Result;
  2893. }, set: function (v) {
  2894. Result = v;
  2895. }})) {
  2896. var $tmp = this.FDuplicates;
  2897. if ($tmp === 0) {
  2898. return Result}
  2899. else if ($tmp === 2) this.Error(rtl.getResStr(pas.RTLConsts,"SDuplicateString"),0);
  2900. };
  2901. this.InsertItem(Result,S);
  2902. return Result;
  2903. };
  2904. this.Find = function (S, Index) {
  2905. var Result = false;
  2906. var L = 0;
  2907. var R = 0;
  2908. var I = 0;
  2909. var CompareRes = 0;
  2910. Result = false;
  2911. Index.set(-1);
  2912. if (!this.GetSorted()) throw $mod.EListError.$create("Create$1",[rtl.getResStr(pas.RTLConsts,"SErrFindNeedsSortedList")]);
  2913. L = 0;
  2914. R = this.GetCount() - 1;
  2915. while (L <= R) {
  2916. I = L + rtl.trunc((R - L) / 2);
  2917. CompareRes = this.DoCompareText(S,this.FList[I].FString);
  2918. if (CompareRes > 0) {
  2919. L = I + 1}
  2920. else {
  2921. R = I - 1;
  2922. if (CompareRes === 0) {
  2923. Result = true;
  2924. if (this.FDuplicates !== 1) L = I;
  2925. };
  2926. };
  2927. };
  2928. Index.set(L);
  2929. return Result;
  2930. };
  2931. this.IndexOf = function (S) {
  2932. var Result = 0;
  2933. if (!this.GetSorted()) {
  2934. Result = $mod.TStrings.IndexOf.call(this,S)}
  2935. else if (!this.Find(S,{get: function () {
  2936. return Result;
  2937. }, set: function (v) {
  2938. Result = v;
  2939. }})) Result = -1;
  2940. return Result;
  2941. };
  2942. this.Insert = function (Index, S) {
  2943. if (this.FSortStyle === 2) {
  2944. this.Error(rtl.getResStr(pas.RTLConsts,"SSortedListError"),0)}
  2945. else {
  2946. if ((Index < 0) || (Index > this.FCount)) this.Error(rtl.getResStr(pas.RTLConsts,"SListIndexError"),Index);
  2947. this.InsertItem(Index,S);
  2948. };
  2949. };
  2950. });
  2951. this.TOperation = {"0": "opInsert", opInsert: 0, "1": "opRemove", opRemove: 1};
  2952. 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};
  2953. this.TComponentStyleItem = {"0": "csInheritable", csInheritable: 0, "1": "csCheckPropAvail", csCheckPropAvail: 1, "2": "csSubComponent", csSubComponent: 2, "3": "csTransient", csTransient: 3};
  2954. rtl.createClass(this,"TComponent",this.TPersistent,function () {
  2955. this.$init = function () {
  2956. $mod.TPersistent.$init.call(this);
  2957. this.FOwner = null;
  2958. this.FName = "";
  2959. this.FTag = 0;
  2960. this.FComponents = null;
  2961. this.FFreeNotifies = null;
  2962. this.FComponentState = {};
  2963. this.FComponentStyle = {};
  2964. };
  2965. this.$final = function () {
  2966. this.FOwner = undefined;
  2967. this.FComponents = undefined;
  2968. this.FFreeNotifies = undefined;
  2969. this.FComponentState = undefined;
  2970. this.FComponentStyle = undefined;
  2971. $mod.TPersistent.$final.call(this);
  2972. };
  2973. this.Insert = function (AComponent) {
  2974. if (!(this.FComponents != null)) this.FComponents = $mod.TFPList.$create("Create");
  2975. this.FComponents.Add(AComponent);
  2976. AComponent.FOwner = this;
  2977. };
  2978. this.Remove = function (AComponent) {
  2979. AComponent.FOwner = null;
  2980. if (this.FComponents != null) {
  2981. this.FComponents.Remove(AComponent);
  2982. if (this.FComponents.FCount === 0) {
  2983. this.FComponents.$destroy("Destroy");
  2984. this.FComponents = null;
  2985. };
  2986. };
  2987. };
  2988. this.RemoveNotification = function (AComponent) {
  2989. if (this.FFreeNotifies !== null) {
  2990. this.FFreeNotifies.Remove(AComponent);
  2991. if (this.FFreeNotifies.FCount === 0) {
  2992. this.FFreeNotifies.$destroy("Destroy");
  2993. this.FFreeNotifies = null;
  2994. this.FComponentState = rtl.excludeSet(this.FComponentState,8);
  2995. };
  2996. };
  2997. };
  2998. this.SetReference = function (Enable) {
  2999. var aField = null;
  3000. var aValue = null;
  3001. var aOwner = null;
  3002. if (this.FName === "") return;
  3003. if (this.FOwner != null) {
  3004. aOwner = this.FOwner;
  3005. aField = this.FOwner.$class.FieldAddress(this.FName);
  3006. if (aField != null) {
  3007. if (Enable) {
  3008. aValue = this}
  3009. else aValue = null;
  3010. aOwner["" + aField["name"]] = aValue;
  3011. };
  3012. };
  3013. };
  3014. this.ChangeName = function (NewName) {
  3015. this.FName = NewName;
  3016. };
  3017. this.Notification = function (AComponent, Operation) {
  3018. var C = 0;
  3019. if (Operation === 1) this.RemoveFreeNotification(AComponent);
  3020. if (!(this.FComponents != null)) return;
  3021. C = this.FComponents.FCount - 1;
  3022. while (C >= 0) {
  3023. rtl.getObject(this.FComponents.Get(C)).Notification(AComponent,Operation);
  3024. C -= 1;
  3025. if (C >= this.FComponents.FCount) C = this.FComponents.FCount - 1;
  3026. };
  3027. };
  3028. this.SetDesigning = function (Value, SetChildren) {
  3029. var Runner = 0;
  3030. if (Value) {
  3031. this.FComponentState = rtl.includeSet(this.FComponentState,4)}
  3032. else this.FComponentState = rtl.excludeSet(this.FComponentState,4);
  3033. if ((this.FComponents != null) && SetChildren) for (var $l = 0, $end = this.FComponents.FCount - 1; $l <= $end; $l++) {
  3034. Runner = $l;
  3035. rtl.getObject(this.FComponents.Get(Runner)).SetDesigning(Value,true);
  3036. };
  3037. };
  3038. this.SetName = function (NewName) {
  3039. if (this.FName === NewName) return;
  3040. if ((NewName !== "") && !pas.SysUtils.IsValidIdent(NewName,false,false)) throw $mod.EComponentError.$create("CreateFmt",[rtl.getResStr(pas.RTLConsts,"SInvalidName"),pas.System.VarRecs(18,NewName)]);
  3041. if (this.FOwner != null) {
  3042. this.FOwner.ValidateRename(this,this.FName,NewName)}
  3043. else this.ValidateRename(null,this.FName,NewName);
  3044. this.SetReference(false);
  3045. this.ChangeName(NewName);
  3046. this.SetReference(true);
  3047. };
  3048. this.ValidateRename = function (AComponent, CurName, NewName) {
  3049. 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)]);
  3050. if ((4 in this.FComponentState) && (this.FOwner !== null)) this.FOwner.ValidateRename(AComponent,CurName,NewName);
  3051. };
  3052. this.ValidateContainer = function (AComponent) {
  3053. AComponent.ValidateInsert(this);
  3054. };
  3055. this.ValidateInsert = function (AComponent) {
  3056. if (AComponent === null) ;
  3057. };
  3058. this.Create$1 = function (AOwner) {
  3059. this.FComponentStyle = rtl.createSet(0);
  3060. if (AOwner != null) AOwner.InsertComponent(this);
  3061. return this;
  3062. };
  3063. this.Destroy = function () {
  3064. var I = 0;
  3065. var C = null;
  3066. this.Destroying();
  3067. if (this.FFreeNotifies != null) {
  3068. I = this.FFreeNotifies.FCount - 1;
  3069. while (I >= 0) {
  3070. C = rtl.getObject(this.FFreeNotifies.Get(I));
  3071. this.FFreeNotifies.Delete(I);
  3072. C.Notification(this,1);
  3073. if (this.FFreeNotifies === null) {
  3074. I = 0}
  3075. else if (I > this.FFreeNotifies.FCount) I = this.FFreeNotifies.FCount;
  3076. I -= 1;
  3077. };
  3078. pas.SysUtils.FreeAndNil({p: this, get: function () {
  3079. return this.p.FFreeNotifies;
  3080. }, set: function (v) {
  3081. this.p.FFreeNotifies = v;
  3082. }});
  3083. };
  3084. this.DestroyComponents();
  3085. if (this.FOwner !== null) this.FOwner.RemoveComponent(this);
  3086. pas.System.TObject.Destroy.call(this);
  3087. };
  3088. this.BeforeDestruction = function () {
  3089. if (!(3 in this.FComponentState)) this.Destroying();
  3090. };
  3091. this.DestroyComponents = function () {
  3092. var acomponent = null;
  3093. while (this.FComponents != null) {
  3094. acomponent = rtl.getObject(this.FComponents.Last());
  3095. this.Remove(acomponent);
  3096. acomponent.$destroy("Destroy");
  3097. };
  3098. };
  3099. this.Destroying = function () {
  3100. var Runner = 0;
  3101. if (3 in this.FComponentState) return;
  3102. this.FComponentState = rtl.includeSet(this.FComponentState,3);
  3103. if (this.FComponents != null) for (var $l = 0, $end = this.FComponents.FCount - 1; $l <= $end; $l++) {
  3104. Runner = $l;
  3105. rtl.getObject(this.FComponents.Get(Runner)).Destroying();
  3106. };
  3107. };
  3108. this.FindComponent = function (AName) {
  3109. var Result = null;
  3110. var I = 0;
  3111. Result = null;
  3112. if ((AName === "") || !(this.FComponents != null)) return Result;
  3113. for (var $l = 0, $end = this.FComponents.FCount - 1; $l <= $end; $l++) {
  3114. I = $l;
  3115. if (pas.SysUtils.CompareText(rtl.getObject(this.FComponents.Get(I)).FName,AName) === 0) {
  3116. Result = rtl.getObject(this.FComponents.Get(I));
  3117. return Result;
  3118. };
  3119. };
  3120. return Result;
  3121. };
  3122. this.RemoveFreeNotification = function (AComponent) {
  3123. this.RemoveNotification(AComponent);
  3124. AComponent.RemoveNotification(this);
  3125. };
  3126. this.InsertComponent = function (AComponent) {
  3127. AComponent.ValidateContainer(this);
  3128. this.ValidateRename(AComponent,"",AComponent.FName);
  3129. if (AComponent.FOwner !== null) AComponent.FOwner.RemoveComponent(AComponent);
  3130. this.Insert(AComponent);
  3131. if (4 in this.FComponentState) AComponent.SetDesigning(true,true);
  3132. this.Notification(AComponent,0);
  3133. };
  3134. this.RemoveComponent = function (AComponent) {
  3135. this.Notification(AComponent,1);
  3136. this.Remove(AComponent);
  3137. AComponent.SetDesigning(false,true);
  3138. this.ValidateRename(AComponent,AComponent.FName,"");
  3139. };
  3140. var $r = this.$rtti;
  3141. $r.addProperty("Name",6,rtl.string,"FName","SetName");
  3142. $r.addProperty("Tag",0,rtl.nativeint,"FTag","FTag",{Default: 0});
  3143. });
  3144. $mod.$implcode = function () {
  3145. $impl.ClassList = null;
  3146. };
  3147. $mod.$init = function () {
  3148. $impl.ClassList = new Object();
  3149. };
  3150. },[]);
  3151. rtl.module("webassembly",["System","JS"],function () {
  3152. "use strict";
  3153. var $mod = this;
  3154. rtl.recNewT(this,"TJSWebAssemblyMemoryDescriptor",function () {
  3155. this.initial = 0;
  3156. this.maximum = 0;
  3157. this.shared = false;
  3158. this.$eq = function (b) {
  3159. return (this.initial === b.initial) && (this.maximum === b.maximum) && (this.shared === b.shared);
  3160. };
  3161. this.$assign = function (s) {
  3162. this.initial = s.initial;
  3163. this.maximum = s.maximum;
  3164. this.shared = s.shared;
  3165. return this;
  3166. };
  3167. });
  3168. rtl.recNewT(this,"TJSWebAssemblyTableDescriptor",function () {
  3169. this.element = "";
  3170. this.initial = 0;
  3171. this.maximum = 0;
  3172. this.$eq = function (b) {
  3173. return (this.element === b.element) && (this.initial === b.initial) && (this.maximum === b.maximum);
  3174. };
  3175. this.$assign = function (s) {
  3176. this.element = s.element;
  3177. this.initial = s.initial;
  3178. this.maximum = s.maximum;
  3179. return this;
  3180. };
  3181. });
  3182. });
  3183. rtl.module("wasitypes",["System","JS"],function () {
  3184. "use strict";
  3185. var $mod = this;
  3186. this.WASI_ESUCCESS = 0;
  3187. this.WASI_EBADF = 8;
  3188. this.WASI_EINVAL = 28;
  3189. this.WASI_ENOMEM = 48;
  3190. this.WASI_ENOSYS = 52;
  3191. this.WASI_CLOCK_MONOTONIC = 0;
  3192. this.WASI_CLOCK_PROCESS_CPUTIME_ID = 1;
  3193. this.WASI_CLOCK_REALTIME = 2;
  3194. this.WASI_CLOCK_THREAD_CPUTIME_ID = 3;
  3195. this.WASI_EVENTTYPE_CLOCK = 0;
  3196. this.WASI_STDIN_FILENO = 0;
  3197. this.WASI_STDOUT_FILENO = 1;
  3198. this.WASI_STDERR_FILENO = 2;
  3199. this.__WASI_ERRNO_SUCCESS = 0;
  3200. this.__WASI_ERRNO_2BIG = 1;
  3201. this.__WASI_WHENCE_SET = 0;
  3202. this.__WASI_WHENCE_CUR = 1;
  3203. this.__WASI_WHENCE_END = 2;
  3204. this.__WASI_FILETYPE_UNKNOWN = 0;
  3205. this.__WASI_FILETYPE_BLOCK_DEVICE = 1;
  3206. this.__WASI_FILETYPE_CHARACTER_DEVICE = 2;
  3207. this.__WASI_FILETYPE_DIRECTORY = 3;
  3208. this.__WASI_FILETYPE_REGULAR_FILE = 4;
  3209. this.__WASI_FILETYPE_SOCKET_STREAM = 6;
  3210. this.__WASI_FILETYPE_SYMBOLIC_LINK = 7;
  3211. this.__WASI_FSTFLAGS_ATIM = 1;
  3212. this.__WASI_FSTFLAGS_ATIM_NOW = 2;
  3213. this.__WASI_FSTFLAGS_MTIM = 4;
  3214. this.__WASI_FSTFLAGS_MTIM_NOW = 8;
  3215. rtl.recNewT(this,"__wasi_filestat_t",function () {
  3216. this.dev = 0;
  3217. this.ino = 0;
  3218. this.filetype = 0;
  3219. this.nlink = 0;
  3220. this.size = 0;
  3221. this.atim = 0;
  3222. this.mtim = 0;
  3223. this.ctim = 0;
  3224. this.$eq = function (b) {
  3225. 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);
  3226. };
  3227. this.$assign = function (s) {
  3228. this.dev = s.dev;
  3229. this.ino = s.ino;
  3230. this.filetype = s.filetype;
  3231. this.nlink = s.nlink;
  3232. this.size = s.size;
  3233. this.atim = s.atim;
  3234. this.mtim = s.mtim;
  3235. this.ctim = s.ctim;
  3236. return this;
  3237. };
  3238. });
  3239. 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};
  3240. rtl.recNewT(this,"TWasiFSDirent",function () {
  3241. this.ino = 0;
  3242. this.name = "";
  3243. this.EntryType = 0;
  3244. this.next = 0;
  3245. this.$eq = function (b) {
  3246. return (this.ino === b.ino) && (this.name === b.name) && (this.EntryType === b.EntryType) && (this.next === b.next);
  3247. };
  3248. this.$assign = function (s) {
  3249. this.ino = s.ino;
  3250. this.name = s.name;
  3251. this.EntryType = s.EntryType;
  3252. this.next = s.next;
  3253. return this;
  3254. };
  3255. });
  3256. this.TSeekWhence = {"0": "swBeginning", swBeginning: 0, "1": "swCurrent", swCurrent: 1, "2": "swEnd", swEnd: 2};
  3257. this.TSetTimesFlag = {"0": "stfatime", stfatime: 0, "1": "stfaTimeNow", stfaTimeNow: 1, "2": "stfmTime", stfmTime: 2, "3": "stfmTimeNow", stfmTimeNow: 3};
  3258. 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);
  3259. this.DirentMap = [0,4,3,7,6,1,2,0];
  3260. });
  3261. rtl.module("weborworker",["System","JS","Types"],function () {
  3262. "use strict";
  3263. var $mod = this;
  3264. this.isMainBrowserThread = function () {
  3265. return (typeof window !== "undefined");
  3266. };
  3267. this.isWebWorker = function () {
  3268. return (typeof DedicatedWorkerGlobalScope !== 'undefined') &&
  3269. (self instanceof DedicatedWorkerGlobalScope);
  3270. };
  3271. this.IsServiceWorker = function () {
  3272. return (typeof ServiceWorkerGlobalScope !== 'undefined') && (self instanceof ServiceWorkerGlobalScope);
  3273. };
  3274. });
  3275. rtl.module("wasienv",["System","SysUtils","Classes","JS","webassembly","Types","wasitypes"],function () {
  3276. "use strict";
  3277. var $mod = this;
  3278. var $impl = $mod.$impl;
  3279. this.SizeInt8 = 1;
  3280. this.SizeInt32 = 4;
  3281. this.SizeInt64 = 8;
  3282. this.SizeUInt8 = 1;
  3283. this.SizeUInt32 = 4;
  3284. this.SizeUInt64 = 8;
  3285. rtl.createClass(this,"EWasmNativeException",pas.SysUtils.Exception,function () {
  3286. this.$init = function () {
  3287. pas.SysUtils.Exception.$init.call(this);
  3288. this.FNativeClass = "";
  3289. this.FNativeMessage = "";
  3290. };
  3291. this.create$2 = function (aNativeClass, aNativeMessage) {
  3292. pas.SysUtils.Exception.CreateFmt.call(this,"Webassembly code raised an exception %s : %s",pas.System.VarRecs(18,aNativeClass,18,aNativeMessage));
  3293. this.FNativeClass = aNativeClass;
  3294. this.FNativeMessage = aNativeMessage;
  3295. return this;
  3296. };
  3297. });
  3298. rtl.createClass(this,"EWasiFSError",pas.SysUtils.Exception,function () {
  3299. this.$init = function () {
  3300. pas.SysUtils.Exception.$init.call(this);
  3301. this.FErrorcode = 0;
  3302. };
  3303. });
  3304. rtl.recNewT(this,"TLastExceptionInfo",function () {
  3305. this.ClassName = "";
  3306. this.Message = "";
  3307. this.more = false;
  3308. this.doraise = false;
  3309. this.$eq = function (b) {
  3310. return (this.ClassName === b.ClassName) && (this.Message === b.Message) && (this.more === b.more) && (this.doraise === b.doraise);
  3311. };
  3312. this.$assign = function (s) {
  3313. this.ClassName = s.ClassName;
  3314. this.Message = s.Message;
  3315. this.more = s.more;
  3316. this.doraise = s.doraise;
  3317. return this;
  3318. };
  3319. });
  3320. rtl.createClass(this,"TPas2JSWASIEnvironment",pas.System.TObject,function () {
  3321. this.UTF8TextDecoder = null;
  3322. this.UTF8TextEncoder = null;
  3323. this.IsLittleEndian = true;
  3324. this.$init = function () {
  3325. pas.System.TObject.$init.call(this);
  3326. this.FArguments = null;
  3327. this.FEnvironment = null;
  3328. this.FExitCode = 0;
  3329. this.FImportObject = null;
  3330. this.Finstance = null;
  3331. this.FLogAPI = false;
  3332. this.FModuleInstanceExports = null;
  3333. this.FOnGetConsoleInputBuffer = null;
  3334. this.FOnGetConsoleInputString = null;
  3335. this.FOnStdErrorWrite = null;
  3336. this.FOnStdOutputWrite = null;
  3337. this.FImportExtensions = null;
  3338. this.FWasiFS = null;
  3339. this.FWASIImportName = "";
  3340. this.FMemory = null;
  3341. };
  3342. this.$final = function () {
  3343. this.FArguments = undefined;
  3344. this.FEnvironment = undefined;
  3345. this.FImportObject = undefined;
  3346. this.Finstance = undefined;
  3347. this.FModuleInstanceExports = undefined;
  3348. this.FOnGetConsoleInputBuffer = undefined;
  3349. this.FOnGetConsoleInputString = undefined;
  3350. this.FOnStdErrorWrite = undefined;
  3351. this.FOnStdOutputWrite = undefined;
  3352. this.FImportExtensions = undefined;
  3353. this.FWasiFS = undefined;
  3354. this.FMemory = undefined;
  3355. pas.System.TObject.$final.call(this);
  3356. };
  3357. this.DoRead = function (fd, iovs, iovsLen, atPos, nread) {
  3358. var $Self = this;
  3359. var Result = 0;
  3360. var view = null;
  3361. var avail = 0;
  3362. var bytesRead = 0;
  3363. var ReadBuffer = null;
  3364. var WasiBuffers = [];
  3365. var TotalBufSize = 0;
  3366. function readv(element, index, anArray) {
  3367. var Result = false;
  3368. var b = 0;
  3369. b = 0;
  3370. while ((b < element.byteLength) && (bytesRead < avail)) {
  3371. element[b] = ReadBuffer[bytesRead];
  3372. b += 1;
  3373. bytesRead += 1;
  3374. };
  3375. Result = true;
  3376. return Result;
  3377. };
  3378. TotalBufSize = 0;
  3379. bytesRead = 0;
  3380. view = this.getModuleMemoryDataView();
  3381. WasiBuffers = this.getiovs(view,iovs,iovsLen);
  3382. TotalBufSize = this.GetTotalIOVsLen(rtl.arrayRef(WasiBuffers));
  3383. if (fd === 0) {
  3384. ReadBuffer = this.GetConsoleInputBuffer(TotalBufSize);
  3385. avail = ReadBuffer.byteLength;
  3386. } else if (this.FWasiFS != null) {
  3387. try {
  3388. ReadBuffer = new Uint8Array(new ArrayBuffer(TotalBufSize));
  3389. Result = this.FWasiFS.Read(fd,ReadBuffer,atPos,{get: function () {
  3390. return avail;
  3391. }, set: function (v) {
  3392. avail = v;
  3393. }});
  3394. if (Result !== 0) return Result;
  3395. } catch ($e) {
  3396. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3397. var E = $e;
  3398. Result = this.$class.ErrorToCode(E);
  3399. } else throw $e
  3400. }}
  3401. else {
  3402. ReadBuffer = this.GetFileBuffer(fd,TotalBufSize);
  3403. avail = ReadBuffer.byteLength;
  3404. };
  3405. if (avail > 0) WasiBuffers.forEach(readv);
  3406. view.setUint32(nread,bytesRead,true);
  3407. Result = 0;
  3408. return Result;
  3409. };
  3410. this.GetConsoleInputBuffer = function (aMaxSize) {
  3411. var Result = null;
  3412. var S = "";
  3413. Result = null;
  3414. if (this.FOnGetConsoleInputBuffer != null) {
  3415. this.FOnGetConsoleInputBuffer(this,{get: function () {
  3416. return Result;
  3417. }, set: function (v) {
  3418. Result = v;
  3419. }})}
  3420. else if (this.FOnGetConsoleInputString != null) {
  3421. S = "";
  3422. this.FOnGetConsoleInputString(this,{get: function () {
  3423. return S;
  3424. }, set: function (v) {
  3425. S = v;
  3426. }});
  3427. S = pas.System.Copy(S,1,aMaxSize);
  3428. Result = $impl.toUTF8Array(S);
  3429. } else Result = new Uint8Array(0);
  3430. return Result;
  3431. };
  3432. this.GetFileBuffer = function (FD, aMaxLen) {
  3433. var Result = null;
  3434. Result = new Uint8Array(0);
  3435. return Result;
  3436. };
  3437. this.GetImportObject = function () {
  3438. var Result = null;
  3439. if (!(this.FImportObject != null)) {
  3440. this.FImportObject = new Object();
  3441. this.GetImports(this.FImportObject);
  3442. };
  3443. Result = this.FImportObject;
  3444. return Result;
  3445. };
  3446. this.getiovs = function (view, iovs, iovsLen) {
  3447. var Result = [];
  3448. var I = 0;
  3449. var ArrayBuf = null;
  3450. var Ptr = 0;
  3451. var Buf = 0;
  3452. var BufLen = 0;
  3453. Result = rtl.arraySetLength(Result,null,iovsLen);
  3454. Ptr = iovs;
  3455. for (var $l = 0, $end = iovsLen - 1; $l <= $end; $l++) {
  3456. I = $l;
  3457. Buf = view.getUint32(Ptr,true);
  3458. BufLen = view.getUint32(Ptr + 4,true);
  3459. ArrayBuf = new Uint8Array(this.GetMemory().buffer,Buf,BufLen);
  3460. Result[I] = ArrayBuf;
  3461. Ptr += 8;
  3462. };
  3463. return Result;
  3464. };
  3465. this.GetTotalIOVsLen = function (iovs) {
  3466. var $Self = this;
  3467. var Result = 0;
  3468. var BufLen = 0;
  3469. function calclen(element, index, anArray) {
  3470. var Result = false;
  3471. BufLen = BufLen + element.byteLength;
  3472. Result = true;
  3473. return Result;
  3474. };
  3475. iovs.forEach(calclen);
  3476. Result = BufLen;
  3477. return Result;
  3478. };
  3479. this.GetIOVsAsBytes = function (iovs, iovsLen) {
  3480. var $Self = this;
  3481. var Result = null;
  3482. var view = null;
  3483. var buflen = 0;
  3484. var Written = 0;
  3485. var bufferBytes = null;
  3486. var Buffers = [];
  3487. var Buf = null;
  3488. function writev(element, index, anArray) {
  3489. var Result = false;
  3490. Buf.set(element,Written);
  3491. Written += element.byteLength;
  3492. Result = true;
  3493. return Result;
  3494. };
  3495. view = this.getModuleMemoryDataView();
  3496. Written = 0;
  3497. buflen = 0;
  3498. Buffers = this.getiovs(view,iovs,iovsLen);
  3499. buflen = this.GetTotalIOVsLen(rtl.arrayRef(Buffers));
  3500. bufferBytes = new ArrayBuffer(buflen);
  3501. Buf = new Uint8Array(bufferBytes);
  3502. Buffers.forEach(writev);
  3503. Result = Buf;
  3504. return Result;
  3505. };
  3506. this.GetMemory = function () {
  3507. var Result = null;
  3508. Result = this.FModuleInstanceExports.memory;
  3509. return Result;
  3510. };
  3511. this.SetInstance = function (AValue) {
  3512. if (this.Finstance === AValue) return;
  3513. this.Finstance = AValue;
  3514. this.FModuleInstanceExports = this.Finstance.exports;
  3515. if (!(this.FMemory != null) && (this.FModuleInstanceExports.memory != null)) this.FMemory = this.FModuleInstanceExports.memory;
  3516. };
  3517. this.WriteFileStatToMem = function (BufPtr, Info) {
  3518. var Loc = 0;
  3519. Loc = BufPtr;
  3520. Loc = this.SetMemInfoInt64(Loc,Info.dev);
  3521. Loc = this.SetMemInfoUInt64(Loc,Info.ino);
  3522. Loc = this.SetMemInfoUInt64(Loc,Info.filetype);
  3523. Loc = this.SetMemInfoUInt64(Loc,Info.nlink);
  3524. Loc = this.SetMemInfoUInt64(Loc,Info.size);
  3525. Loc = this.SetMemInfoUInt64(Loc,Info.atim * 1000 * 1000);
  3526. Loc = this.SetMemInfoUInt64(Loc,Info.mtim * 1000 * 1000);
  3527. Loc = this.SetMemInfoUInt64(Loc,Info.ctim * 1000 * 1000);
  3528. };
  3529. this.ErrorToCode = function (E) {
  3530. var Result = 0;
  3531. var EW = null;
  3532. if ($mod.EWasiFSError.isPrototypeOf(E)) {
  3533. Result = EW.FErrorcode}
  3534. else Result = 0;
  3535. if (Result === 0) Result = 52;
  3536. return Result;
  3537. };
  3538. this.DoLog$1 = function (Fmt, Args) {
  3539. pas.System.Writeln(pas.SysUtils.Format(Fmt,Args));
  3540. };
  3541. this.setBigUint64 = function (View, byteOffset, value, littleEndian) {
  3542. var LowWord = 0;
  3543. var HighWord = 0;
  3544. LowWord = value;
  3545. HighWord = Math.floor(value / 4294967296);
  3546. if (littleEndian) {
  3547. View.setUint32(byteOffset + 0,LowWord,littleEndian);
  3548. View.setUint32(byteOffset + 4,HighWord,littleEndian);
  3549. } else {
  3550. View.setUint32(byteOffset + 4,LowWord,littleEndian);
  3551. View.setUint32(byteOffset + 0,HighWord,littleEndian);
  3552. };
  3553. };
  3554. this.setBigInt64 = function (View, byteOffset, value, littleEndian) {
  3555. var LowWord = 0;
  3556. var HighWord = 0;
  3557. LowWord = value;
  3558. HighWord = Math.floor(value / 4294967296);
  3559. if (littleEndian) {
  3560. View.setInt32(byteOffset + 0,LowWord,littleEndian);
  3561. View.setInt32(byteOffset + 4,HighWord,littleEndian);
  3562. } else {
  3563. View.setInt32(byteOffset + 4,LowWord,littleEndian);
  3564. View.setInt32(byteOffset + 0,HighWord,littleEndian);
  3565. };
  3566. };
  3567. this.DoConsoleWrite = function (IsStdErr, aBytes) {
  3568. var $Self = this;
  3569. function TryConvert() {
  3570. var Result = "";
  3571. Result = "";
  3572. Result=String.fromCharCode.apply(null, aBytes);
  3573. return Result;
  3574. };
  3575. var S = "";
  3576. var Evt = null;
  3577. try {
  3578. S = this.GetUTF8StringFromArray(aBytes);
  3579. } catch ($e) {
  3580. S = TryConvert();
  3581. };
  3582. if (IsStdErr) {
  3583. Evt = this.FOnStdErrorWrite}
  3584. else Evt = this.FOnStdOutputWrite;
  3585. if (Evt != null) Evt($Self,S);
  3586. };
  3587. this.GetImports = function (aImports) {
  3588. aImports["args_get"] = rtl.createCallback(this,"args_get");
  3589. aImports["args_sizes_get"] = rtl.createCallback(this,"args_sizes_get");
  3590. aImports["clock_res_get"] = rtl.createCallback(this,"clock_res_get");
  3591. aImports["clock_time_get"] = rtl.createCallback(this,"clock_time_get");
  3592. aImports["environ_get"] = rtl.createCallback(this,"environ_get");
  3593. aImports["environ_sizes_get"] = rtl.createCallback(this,"environ_sizes_get");
  3594. aImports["fd_advise"] = rtl.createCallback(this,"fd_advise");
  3595. aImports["fd_allocate"] = rtl.createCallback(this,"fd_allocate");
  3596. aImports["fd_close"] = rtl.createCallback(this,"fd_close");
  3597. aImports["fd_datasync"] = rtl.createCallback(this,"fd_datasync");
  3598. aImports["fd_fdstat_get"] = rtl.createCallback(this,"fd_fdstat_get");
  3599. aImports["fd_fdstat_set_flags"] = rtl.createCallback(this,"fd_fdstat_set_flags");
  3600. aImports["fd_fdstat_set_rights"] = rtl.createCallback(this,"fd_fdstat_set_rights");
  3601. aImports["fd_filestat_get"] = rtl.createCallback(this,"fd_filestat_get");
  3602. aImports["fd_filestat_set_size"] = rtl.createCallback(this,"fd_filestat_set_size");
  3603. aImports["fd_filestat_set_times"] = rtl.createCallback(this,"fd_filestat_set_times");
  3604. aImports["fd_pread"] = rtl.createCallback(this,"fd_pread");
  3605. aImports["fd_prestat_dir_name"] = rtl.createCallback(this,"fd_prestat_dir_name");
  3606. aImports["fd_prestat_get"] = rtl.createCallback(this,"fd_prestat_get");
  3607. aImports["fd_pwrite"] = rtl.createCallback(this,"fd_pwrite");
  3608. aImports["fd_read"] = rtl.createCallback(this,"fd_read");
  3609. aImports["fd_readdir"] = rtl.createCallback(this,"fd_readdir");
  3610. aImports["fd_renumber"] = rtl.createCallback(this,"fd_renumber");
  3611. aImports["fd_seek"] = rtl.createCallback(this,"fd_seek");
  3612. aImports["fd_sync"] = rtl.createCallback(this,"fd_sync");
  3613. aImports["fd_tell"] = rtl.createCallback(this,"fd_tell");
  3614. aImports["fd_write"] = rtl.createCallback(this,"fd_write");
  3615. aImports["path_create_directory"] = rtl.createCallback(this,"path_create_directory");
  3616. aImports["path_filestat_get"] = rtl.createCallback(this,"path_filestat_get");
  3617. aImports["path_filestat_set_times"] = rtl.createCallback(this,"path_filestat_set_times");
  3618. aImports["path_link"] = rtl.createCallback(this,"path_link");
  3619. aImports["path_open"] = rtl.createCallback(this,"path_open");
  3620. aImports["path_readlink"] = rtl.createCallback(this,"path_readlink");
  3621. aImports["path_remove_directory"] = rtl.createCallback(this,"path_remove_directory");
  3622. aImports["path_rename"] = rtl.createCallback(this,"path_rename");
  3623. aImports["path_symlink"] = rtl.createCallback(this,"path_symlink");
  3624. aImports["path_unlink_file"] = rtl.createCallback(this,"path_unlink_file");
  3625. aImports["poll_oneoff"] = rtl.createCallback(this,"poll_oneoff");
  3626. aImports["proc_exit"] = rtl.createCallback(this,"proc_exit");
  3627. aImports["proc_raise"] = rtl.createCallback(this,"proc_raise");
  3628. aImports["random_get"] = rtl.createCallback(this,"random_get");
  3629. aImports["sched_yield"] = rtl.createCallback(this,"sched_yield");
  3630. aImports["sock_recv"] = rtl.createCallback(this,"sock_recv");
  3631. aImports["sock_send"] = rtl.createCallback(this,"sock_send");
  3632. aImports["sock_shutdown"] = rtl.createCallback(this,"sock_shutdown");
  3633. };
  3634. this.GetTime = function (aClockID) {
  3635. var Result = 0;
  3636. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.GetTime(%d)",pas.System.VarRecs(19,aClockID));
  3637. Result = -1;
  3638. var $tmp = aClockID;
  3639. if ($tmp === 0) {
  3640. Result = Date.now()}
  3641. else if ($tmp === 2) {
  3642. Result = Date.now()}
  3643. else if (($tmp === 1) || ($tmp === 3)) Result = Date.now();
  3644. Result = Result * 1000000;
  3645. return Result;
  3646. };
  3647. this.getModuleMemoryDataView = function () {
  3648. var Result = null;
  3649. Result = new DataView(this.GetMemory().buffer);
  3650. return Result;
  3651. };
  3652. this.AddExtension = function (aExtension) {
  3653. if (!(this.FImportExtensions != null)) this.FImportExtensions = pas.Classes.TFPList.$create("Create");
  3654. this.FImportExtensions.Add(aExtension);
  3655. };
  3656. this.RemoveExtension = function (aExtension) {
  3657. if (this.FImportExtensions != null) this.FImportExtensions.Remove(aExtension);
  3658. };
  3659. this.args_get = function (argv, argvBuf) {
  3660. var Result = 0;
  3661. var Ptr = 0;
  3662. var PtrV = 0;
  3663. var S = "";
  3664. var i = 0;
  3665. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.args_get([%x],[%x])",pas.System.VarRecs(0,argv,0,argvBuf));
  3666. Ptr = argvBuf;
  3667. PtrV = argv;
  3668. for (var $l = 0, $end = this.FArguments.GetCount() - 1; $l <= $end; $l++) {
  3669. i = $l;
  3670. S = this.FArguments.Get(i);
  3671. PtrV = this.SetMemInfoUInt32(PtrV,Ptr);
  3672. Ptr = Ptr + this.SetUTF8StringInMem(Ptr,S.length,S);
  3673. Ptr = this.SetMemInfoUInt8(Ptr,0);
  3674. };
  3675. Result = 0;
  3676. return Result;
  3677. };
  3678. this.args_sizes_get = function (argc, argvBufSize) {
  3679. var Result = 0;
  3680. var View = null;
  3681. var Size = 0;
  3682. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.args_sizes_get([%x],[%x])",pas.System.VarRecs(0,argc,0,argvBufSize));
  3683. View = this.getModuleMemoryDataView();
  3684. View.setUint32(argc,this.FArguments.GetCount(),true);
  3685. Size = 0;
  3686. if (this.FArguments.GetCount() > 0) Size = this.FArguments.GetTextStr().length + 1;
  3687. View.setUint32(argvBufSize,Size,true);
  3688. Result = 0;
  3689. return Result;
  3690. };
  3691. this.clock_res_get = function (clockId, resolution) {
  3692. var Result = 0;
  3693. var view = null;
  3694. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.clock_res_get(%d,%d)",pas.System.VarRecs(19,clockId,19,resolution));
  3695. view = this.getModuleMemoryDataView();
  3696. this.$class.setBigUint64(view,resolution,0,true);
  3697. Result = 0;
  3698. return Result;
  3699. };
  3700. this.clock_time_get = function (clockId, precision, time) {
  3701. var Result = 0;
  3702. var view = null;
  3703. var n = 0;
  3704. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.clock_time_get(%d,%d,[%x])",pas.System.VarRecs(19,clockId,19,precision,0,time));
  3705. view = this.getModuleMemoryDataView();
  3706. n = this.GetTime(clockId);
  3707. if (n === -1) {
  3708. Result = 28}
  3709. else {
  3710. this.$class.setBigUint64(view,time,n,true);
  3711. Result = 0;
  3712. };
  3713. return Result;
  3714. };
  3715. this.environ_get = function (environ, environBuf) {
  3716. var Result = 0;
  3717. var S = "";
  3718. var I = 0;
  3719. var PtrV = 0;
  3720. var Ptr = 0;
  3721. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.environ_get([%x],[%x])",pas.System.VarRecs(0,environ,0,environBuf));
  3722. Ptr = environBuf;
  3723. PtrV = environ;
  3724. for (var $l = 0, $end = this.FEnvironment.GetCount() - 1; $l <= $end; $l++) {
  3725. I = $l;
  3726. S = this.FEnvironment.Get(I);
  3727. PtrV = this.SetMemInfoUInt32(PtrV,Ptr);
  3728. Ptr = Ptr + this.SetUTF8StringInMem(Ptr,S.length,S);
  3729. Ptr = this.SetMemInfoUInt8(Ptr,0);
  3730. };
  3731. Result = 0;
  3732. return Result;
  3733. };
  3734. this.environ_sizes_get = function (environCount, environBufSize) {
  3735. var Result = 0;
  3736. var View = null;
  3737. var Size = 0;
  3738. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.environ_sizes_get([%x],[%x])",pas.System.VarRecs(0,environCount,0,environBufSize));
  3739. View = this.getModuleMemoryDataView();
  3740. View.setUint32(environCount,this.FEnvironment.GetCount(),true);
  3741. Size = 0;
  3742. if (this.FEnvironment.GetCount() > 0) Size = this.FEnvironment.GetTextStr().length + 1;
  3743. View.setUint32(environBufSize,Size,true);
  3744. Result = 0;
  3745. return Result;
  3746. };
  3747. this.fd_advise = function (fd, offset, len, advice) {
  3748. var Result = 0;
  3749. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_advise(%d,%d,%d,%d)",pas.System.VarRecs(19,fd,19,offset,19,len,19,advice));
  3750. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_advise");
  3751. Result = 52;
  3752. return Result;
  3753. };
  3754. this.fd_allocate = function (fd, offset, len) {
  3755. var Result = 0;
  3756. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_allocate(%d,%d,%d)",pas.System.VarRecs(19,fd,19,offset,19,len));
  3757. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_allocate");
  3758. Result = 52;
  3759. return Result;
  3760. };
  3761. this.fd_close = function (fd) {
  3762. var Result = 0;
  3763. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_close(%d)",pas.System.VarRecs(19,fd));
  3764. if (!(this.FWasiFS != null)) {
  3765. Result = 52}
  3766. else try {
  3767. Result = this.FWasiFS.Close(fd);
  3768. } catch ($e) {
  3769. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3770. var E = $e;
  3771. Result = this.$class.ErrorToCode(E);
  3772. } else throw $e
  3773. };
  3774. return Result;
  3775. };
  3776. this.fd_datasync = function (fd) {
  3777. var Result = 0;
  3778. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_datasync(%d)",pas.System.VarRecs(19,fd));
  3779. if (!(this.FWasiFS != null)) {
  3780. Result = 52}
  3781. else try {
  3782. Result = this.FWasiFS.DataSync(fd);
  3783. } catch ($e) {
  3784. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3785. var E = $e;
  3786. Result = this.$class.ErrorToCode(E);
  3787. } else throw $e
  3788. };
  3789. return Result;
  3790. };
  3791. this.fd_fdstat_get = function (fd, bufPtr) {
  3792. var Result = 0;
  3793. var View = null;
  3794. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_fdstat_get(%d,%d)",pas.System.VarRecs(19,fd,0,bufPtr));
  3795. View = this.getModuleMemoryDataView();
  3796. View.setUint8(bufPtr,fd);
  3797. View.setUint16(bufPtr + 2,0,true);
  3798. View.setUint16(bufPtr + 4,0,true);
  3799. this.$class.setBigUint64(View,bufPtr + 8,0,true);
  3800. this.$class.setBigUint64(View,bufPtr + 8 + 8,0,true);
  3801. Result = 0;
  3802. return Result;
  3803. };
  3804. this.fd_fdstat_set_flags = function (fd, flags) {
  3805. var Result = 0;
  3806. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_fdstat_set_flags(%d,%d)",pas.System.VarRecs(19,fd,19,flags));
  3807. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_fdstat_set_flags");
  3808. Result = 52;
  3809. return Result;
  3810. };
  3811. this.fd_fdstat_set_rights = function (fd, fsRightsBase, fsRightsInheriting) {
  3812. var Result = 0;
  3813. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_fdstat_set_rights(%d,%d,%d)",pas.System.VarRecs(19,fd,19,fsRightsBase,19,fsRightsInheriting));
  3814. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_fdstat_set_rights");
  3815. Result = 52;
  3816. return Result;
  3817. };
  3818. this.fd_filestat_get = function (fd, bufPtr) {
  3819. var Result = 0;
  3820. var Info = pas.wasitypes.__wasi_filestat_t.$new();
  3821. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_filestat_get(%d,[%x])",pas.System.VarRecs(19,fd,0,bufPtr));
  3822. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_filestat_get");
  3823. if (!(this.FWasiFS != null)) {
  3824. Result = 52}
  3825. else try {
  3826. Result = this.FWasiFS.StatFD(fd,Info);
  3827. if (Result === 0) this.WriteFileStatToMem(bufPtr,pas.wasitypes.__wasi_filestat_t.$clone(Info));
  3828. } catch ($e) {
  3829. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3830. var E = $e;
  3831. Result = this.$class.ErrorToCode(E);
  3832. } else throw $e
  3833. };
  3834. return Result;
  3835. };
  3836. this.fd_filestat_set_size = function (fd, stSize) {
  3837. var Result = 0;
  3838. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_filestat_set_size(%d,%d)",pas.System.VarRecs(19,fd,19,stSize));
  3839. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_filestat_set_size");
  3840. Result = 52;
  3841. return Result;
  3842. };
  3843. this.fd_filestat_set_times = function (fd, stAtim, stMtim, fstflags) {
  3844. var $Self = this;
  3845. var Result = 0;
  3846. var Flags = {};
  3847. function MaybeFlag(src, Flag) {
  3848. if ((fstflags & src) === src) Flags = rtl.includeSet(Flags,Flag);
  3849. };
  3850. 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));
  3851. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_filestat_set_times");
  3852. if (!(this.FWasiFS != null)) {
  3853. Result = 52}
  3854. else try {
  3855. MaybeFlag(1,0);
  3856. MaybeFlag(2,1);
  3857. MaybeFlag(4,2);
  3858. MaybeFlag(8,3);
  3859. Result = this.FWasiFS.UTimes(fd,new Date(stAtim),new Date(stMtim),rtl.refSet(Flags));
  3860. } catch ($e) {
  3861. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3862. var E = $e;
  3863. Result = this.$class.ErrorToCode(E);
  3864. } else throw $e
  3865. };
  3866. return Result;
  3867. };
  3868. this.fd_pread = function (fd, iovs, iovsLen, offset, nread) {
  3869. var Result = 0;
  3870. 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));
  3871. Result = this.DoRead(fd,iovs,iovsLen,offset,nread);
  3872. return Result;
  3873. };
  3874. this.fd_prestat_dir_name = function (fd, pathPtr, pathLen) {
  3875. var Result = 0;
  3876. var S = "";
  3877. var Len = 0;
  3878. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_prestat_dir_name(%d,[%d],%d)",pas.System.VarRecs(19,fd,0,pathPtr,19,pathLen));
  3879. if (this.FWasiFS != null) {
  3880. S = this.FWasiFS.GetPrestat(fd);
  3881. if (S !== "") {
  3882. Len = S.length;
  3883. if (Len > pathLen) Len = pathLen;
  3884. this.SetUTF8StringInMem(pathPtr,Len,S);
  3885. Result = 0;
  3886. } else Result = 8;
  3887. } else {
  3888. if (fd === 3) {
  3889. this.SetUTF8StringInMem(pathPtr,1,"/");
  3890. Result = 0;
  3891. } else Result = 8;
  3892. };
  3893. return Result;
  3894. };
  3895. this.fd_prestat_get = function (fd, bufPtr) {
  3896. var Result = 0;
  3897. var S = "";
  3898. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_prestat_get(%d,[%d])",pas.System.VarRecs(19,fd,0,bufPtr));
  3899. if (this.FWasiFS != null) {
  3900. S = this.FWasiFS.GetPrestat(fd);
  3901. if (S !== "") {
  3902. this.SetMemInfoInt32(bufPtr,0);
  3903. this.SetMemInfoInt32(bufPtr + 4,S.length);
  3904. Result = 0;
  3905. } else Result = 8;
  3906. } else {
  3907. if (fd === 3) {
  3908. this.SetMemInfoInt32(bufPtr,0);
  3909. this.SetMemInfoInt32(bufPtr + 4,1);
  3910. Result = 0;
  3911. };
  3912. Result = 8;
  3913. };
  3914. return Result;
  3915. };
  3916. this.fd_pwrite = function (fd, iovs, iovsLen, offset, nwritten) {
  3917. var Result = 0;
  3918. var view = null;
  3919. var Buf = null;
  3920. var written = 0;
  3921. 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));
  3922. if ((fd === 1) || (fd === 2)) {
  3923. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  3924. written = Buf.byteLength;
  3925. this.DoConsoleWrite(fd === 2,Buf);
  3926. view.setUint32(nwritten,written,true);
  3927. Result = 0;
  3928. } else if (!(this.FWasiFS != null)) {
  3929. Result = 52}
  3930. else {
  3931. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  3932. Result = this.FWasiFS.Write(fd,Buf,-1,{get: function () {
  3933. return written;
  3934. }, set: function (v) {
  3935. written = v;
  3936. }});
  3937. if (Result === 0) view.setUint32(nwritten,written,true);
  3938. };
  3939. Result = 52;
  3940. return Result;
  3941. };
  3942. this.fd_read = function (fd, iovs, iovsLen, nread) {
  3943. var Result = 0;
  3944. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_read(%d,[%x],%d,[%x])",pas.System.VarRecs(19,fd,0,iovs,19,iovsLen,0,nread));
  3945. Result = this.DoRead(fd,iovs,iovsLen,-1,nread);
  3946. return Result;
  3947. };
  3948. this.fd_readdir = function (fd, bufPtr, bufLen, cookie, bufusedPtr) {
  3949. var Result = 0;
  3950. var Dirent = pas.wasitypes.TWasiFSDirent.$new();
  3951. var NameArray = null;
  3952. var NameLen = 0;
  3953. var Ptr = 0;
  3954. var Res = 0;
  3955. 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));
  3956. if (!(this.FWasiFS != null)) {
  3957. Result = 52}
  3958. else try {
  3959. Res = this.FWasiFS.ReadDir(fd,pas.JS.AsIntNumber(cookie),Dirent);
  3960. Result = 0;
  3961. Ptr = bufPtr;
  3962. while (((Ptr - bufPtr) < bufLen) && (Res === 0)) {
  3963. NameArray = this.UTF8TextEncoder.encode(Dirent.name);
  3964. NameLen = NameArray.byteLength;
  3965. Ptr = this.SetMemInfoUInt64(Ptr,Dirent.next);
  3966. Ptr = this.SetMemInfoUInt64(Ptr,Dirent.ino);
  3967. Ptr = this.SetMemInfoInt32(Ptr,NameLen);
  3968. Ptr = this.SetMemInfoInt32(Ptr,pas.wasitypes.DirentMap[Dirent.EntryType]);
  3969. if (this.SetUTF8StringInMem(Ptr,bufLen - 18,Dirent.name) !== -1) {
  3970. Ptr = Ptr + NameLen;
  3971. cookie = Dirent.next;
  3972. Res = this.FWasiFS.ReadDir(fd,pas.JS.AsIntNumber(cookie),Dirent);
  3973. } else Res = 48;
  3974. };
  3975. this.SetMemInfoInt32(bufusedPtr,Ptr - bufPtr);
  3976. } catch ($e) {
  3977. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  3978. var E = $e;
  3979. Result = this.$class.ErrorToCode(E);
  3980. } else throw $e
  3981. };
  3982. return Result;
  3983. };
  3984. this.fd_renumber = function (afrom, ato) {
  3985. var Result = 0;
  3986. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_renumber(%d,%d)",pas.System.VarRecs(19,afrom,19,ato));
  3987. console.log("Unimplemented: TPas2JSWASIEnvironment.fd_renumber");
  3988. Result = 52;
  3989. return Result;
  3990. };
  3991. this.fd_seek = function (fd, offset, whence, newOffsetPtr) {
  3992. var Result = 0;
  3993. var lWhence = 0;
  3994. var NewPos = 0;
  3995. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_seek(%d,%d,%d,[%x])",pas.System.VarRecs(19,fd,19,offset,19,whence,0,newOffsetPtr));
  3996. if (!(this.FWasiFS != null)) {
  3997. Result = 52}
  3998. else try {
  3999. lWhence = 0;
  4000. var $tmp = whence;
  4001. if ($tmp === 1) {
  4002. lWhence = 1}
  4003. else if ($tmp === 2) {
  4004. lWhence = 2}
  4005. else if ($tmp === 0) {
  4006. lWhence = 0}
  4007. else {
  4008. Result = 28;
  4009. };
  4010. Result = this.FWasiFS.Seek(fd,offset,lWhence,{get: function () {
  4011. return NewPos;
  4012. }, set: function (v) {
  4013. NewPos = v;
  4014. }});
  4015. if (Result === 0) this.SetMemInfoInt64(newOffsetPtr,NewPos);
  4016. } catch ($e) {
  4017. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4018. var E = $e;
  4019. Result = this.$class.ErrorToCode(E);
  4020. } else throw $e
  4021. };
  4022. return Result;
  4023. };
  4024. this.fd_sync = function (fd) {
  4025. var Result = 0;
  4026. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_sync(%d)",pas.System.VarRecs(19,fd));
  4027. if (!(this.FWasiFS != null)) {
  4028. Result = 52}
  4029. else try {
  4030. Result = this.FWasiFS.Sync(fd);
  4031. } catch ($e) {
  4032. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4033. var E = $e;
  4034. Result = this.$class.ErrorToCode(E);
  4035. } else throw $e
  4036. };
  4037. return Result;
  4038. };
  4039. this.fd_tell = function (fd, offsetPtr) {
  4040. var Result = 0;
  4041. var NewPos = 0;
  4042. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_tell(%d,[%x])",pas.System.VarRecs(19,fd,0,offsetPtr));
  4043. if (!(this.FWasiFS != null)) {
  4044. Result = 52}
  4045. else try {
  4046. Result = this.FWasiFS.Seek(fd,0,1,{get: function () {
  4047. return NewPos;
  4048. }, set: function (v) {
  4049. NewPos = v;
  4050. }});
  4051. if (Result === 0) this.SetMemInfoInt32(offsetPtr,NewPos);
  4052. } catch ($e) {
  4053. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4054. var E = $e;
  4055. Result = this.$class.ErrorToCode(E);
  4056. } else throw $e
  4057. };
  4058. return Result;
  4059. };
  4060. this.fd_write = function (fd, iovs, iovsLen, nwritten) {
  4061. var Result = 0;
  4062. var view = null;
  4063. var Buf = null;
  4064. var written = 0;
  4065. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.fd_write(%d,[%d],%d,[%d])",pas.System.VarRecs(19,fd,19,iovs,19,iovsLen,19,nwritten));
  4066. view = this.getModuleMemoryDataView();
  4067. if ((fd === 1) || (fd === 2)) {
  4068. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  4069. written = Buf.byteLength;
  4070. this.DoConsoleWrite(fd === 2,Buf);
  4071. view.setUint32(nwritten,written,true);
  4072. Result = 0;
  4073. } else if (!(this.FWasiFS != null)) {
  4074. Result = 52}
  4075. else {
  4076. Buf = this.GetIOVsAsBytes(iovs,iovsLen);
  4077. Result = this.FWasiFS.Write(fd,Buf,-1,{get: function () {
  4078. return written;
  4079. }, set: function (v) {
  4080. written = v;
  4081. }});
  4082. if (Result === 0) view.setUint32(nwritten,written,true);
  4083. };
  4084. return Result;
  4085. };
  4086. this.path_create_directory = function (fd, pathPtr, pathLen) {
  4087. var Result = 0;
  4088. var S = "";
  4089. S = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4090. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_create_directory(%d,'%s')",pas.System.VarRecs(19,fd,18,S));
  4091. if (!(this.FWasiFS != null)) {
  4092. Result = 52}
  4093. else try {
  4094. Result = this.FWasiFS.MkDirAt(fd,S);
  4095. } catch ($e) {
  4096. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4097. var E = $e;
  4098. Result = this.$class.ErrorToCode(E);
  4099. } else throw $e
  4100. };
  4101. return Result;
  4102. };
  4103. this.path_filestat_get = function (fd, flags, pathPtr, pathLen, bufPtr) {
  4104. var Result = 0;
  4105. var aPath = "";
  4106. var Info = pas.wasitypes.__wasi_filestat_t.$new();
  4107. aPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4108. 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));
  4109. if (!(this.FWasiFS != null)) {
  4110. Result = 52}
  4111. else try {
  4112. Result = this.FWasiFS.StatAt(fd,aPath,Info);
  4113. if (Result === 0) this.WriteFileStatToMem(bufPtr,pas.wasitypes.__wasi_filestat_t.$clone(Info));
  4114. } catch ($e) {
  4115. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4116. var E = $e;
  4117. Result = this.$class.ErrorToCode(E);
  4118. } else throw $e
  4119. };
  4120. return Result;
  4121. };
  4122. this.path_filestat_set_times = function (fd, fstflags, pathPtr, pathLen, stAtim, stMtim) {
  4123. var Result = 0;
  4124. var aPath = "";
  4125. aPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4126. 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));
  4127. if (!(this.FWasiFS != null)) {
  4128. Result = 52}
  4129. else try {
  4130. Result = this.FWasiFS.UTimesAt(fd,aPath,new Date(stAtim),new Date(stMtim),false);
  4131. } catch ($e) {
  4132. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4133. var E = $e;
  4134. Result = this.$class.ErrorToCode(E);
  4135. } else throw $e
  4136. };
  4137. return Result;
  4138. };
  4139. this.path_link = function (oldFd, oldFlags, oldPath, oldPathLen, newFd, NewPath, newPathLen) {
  4140. var Result = 0;
  4141. var lOld = "";
  4142. var lNew = "";
  4143. lOld = this.GetUTF8StringFromMem(oldPath,oldPathLen);
  4144. lNew = this.GetUTF8StringFromMem(NewPath,newPathLen);
  4145. 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));
  4146. if (!(this.FWasiFS != null)) {
  4147. Result = 52}
  4148. else try {
  4149. Result = this.FWasiFS.LinkAt(oldFd,lOld,newFd,lNew);
  4150. } catch ($e) {
  4151. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4152. var E = $e;
  4153. Result = this.$class.ErrorToCode(E);
  4154. } else throw $e
  4155. };
  4156. return Result;
  4157. };
  4158. this.path_open = function (dirfd, dirflags, pathPtr, pathLen, oflags, fsRightsBase, fsRightsInheriting, fsFlags, fd) {
  4159. var Result = 0;
  4160. var lPath = "";
  4161. var lFD = 0;
  4162. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4163. 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));
  4164. if (!(this.FWasiFS != null)) {
  4165. Result = 52}
  4166. else try {
  4167. Result = this.FWasiFS.OpenAt(dirfd,dirflags,lPath,oflags,fsRightsBase,fsRightsInheriting,fsFlags,{get: function () {
  4168. return lFD;
  4169. }, set: function (v) {
  4170. lFD = v;
  4171. }});
  4172. if (Result === 0) this.SetMemInfoInt32(fd,lFD);
  4173. } catch ($e) {
  4174. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4175. var E = $e;
  4176. Result = this.$class.ErrorToCode(E);
  4177. } else throw $e
  4178. };
  4179. return Result;
  4180. };
  4181. this.path_readlink = function (fd, pathPtr, pathLen, buf, bufLen, bufused) {
  4182. var Result = 0;
  4183. var lTarget = "";
  4184. var lPath = "";
  4185. var Written = 0;
  4186. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4187. 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));
  4188. console.log("Unimplemented: TPas2JSWASIEnvironment.path_readlink");
  4189. if (!(this.FWasiFS != null)) {
  4190. Result = 52}
  4191. else try {
  4192. Result = this.FWasiFS.ReadLinkAt(fd,lPath,{get: function () {
  4193. return lTarget;
  4194. }, set: function (v) {
  4195. lTarget = v;
  4196. }});
  4197. if (Result === 0) {
  4198. Written = this.SetUTF8StringInMem(buf,bufLen,lTarget);
  4199. if (Written === -1) {
  4200. Result = 1}
  4201. else this.SetMemInfoInt32(bufused,Written);
  4202. };
  4203. } catch ($e) {
  4204. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4205. var E = $e;
  4206. Result = this.$class.ErrorToCode(E);
  4207. } else throw $e
  4208. };
  4209. Result = 52;
  4210. return Result;
  4211. };
  4212. this.path_remove_directory = function (fd, pathPtr, pathLen) {
  4213. var Result = 0;
  4214. var lPath = "";
  4215. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4216. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_remove_directory(%d,'%s')",pas.System.VarRecs(19,fd,18,lPath));
  4217. if (!(this.FWasiFS != null)) {
  4218. Result = 52}
  4219. else try {
  4220. Result = this.FWasiFS.RmDirAt(fd,lPath);
  4221. } catch ($e) {
  4222. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4223. var E = $e;
  4224. Result = this.$class.ErrorToCode(E);
  4225. } else throw $e
  4226. };
  4227. return Result;
  4228. };
  4229. this.path_rename = function (oldFd, oldPath, oldPathLen, newFd, newPath, newPathLen) {
  4230. var Result = 0;
  4231. var lOld = "";
  4232. var lNew = "";
  4233. lOld = this.GetUTF8StringFromMem(oldPath,oldPathLen);
  4234. lNew = this.GetUTF8StringFromMem(newPath,newPathLen);
  4235. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_rename(%d,'%s',%d,'%s')",pas.System.VarRecs(19,oldFd,18,lOld,19,newFd,18,lNew));
  4236. if (!(this.FWasiFS != null)) {
  4237. Result = 52}
  4238. else try {
  4239. Result = this.FWasiFS.RenameAt(oldFd,lOld,newFd,lNew);
  4240. } catch ($e) {
  4241. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4242. var E = $e;
  4243. Result = this.$class.ErrorToCode(E);
  4244. } else throw $e
  4245. };
  4246. return Result;
  4247. };
  4248. this.path_symlink = function (oldPath, oldPathLen, fd, newPath, newPathLen) {
  4249. var Result = 0;
  4250. var lOld = "";
  4251. var lNew = "";
  4252. lOld = this.GetUTF8StringFromMem(oldPath,oldPathLen);
  4253. lNew = this.GetUTF8StringFromMem(newPath,newPathLen);
  4254. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_symlink('%s',%d,'%s')",pas.System.VarRecs(18,lOld,19,fd,18,lNew));
  4255. if (!(this.FWasiFS != null)) {
  4256. Result = 52}
  4257. else try {
  4258. Result = this.FWasiFS.SymLinkAt(fd,lOld,lNew);
  4259. } catch ($e) {
  4260. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4261. var E = $e;
  4262. Result = this.$class.ErrorToCode(E);
  4263. } else throw $e
  4264. };
  4265. return Result;
  4266. };
  4267. this.path_unlink_file = function (fd, pathPtr, pathLen) {
  4268. var Result = 0;
  4269. var lPath = "";
  4270. lPath = this.GetUTF8StringFromMem(pathPtr,pathLen);
  4271. if (this.FLogAPI) this.DoLog$1("TPas2JSWASIEnvironment.path_unlink_file(%d,'%s')",pas.System.VarRecs(19,fd,18,lPath));
  4272. if (!(this.FWasiFS != null)) {
  4273. Result = 52}
  4274. else try {
  4275. Result = this.FWasiFS.UnLinkAt(fd,lPath);
  4276. } catch ($e) {
  4277. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4278. var E = $e;
  4279. Result = this.$class.ErrorToCode(E);
  4280. } else throw $e
  4281. };
  4282. return Result;
  4283. };
  4284. var TagOffset = 8;
  4285. var TimeoutOffset = 24;
  4286. var PrecisionOffset = 32;
  4287. this.poll_oneoff = function (sin, sout, nsubscriptions, nevents) {
  4288. var Result = 0;
  4289. var Tag = 0;
  4290. var Precision = null;
  4291. var TimeOut = null;
  4292. var msTimeOut = null;
  4293. var msTimeout32 = 0;
  4294. var arr = null;
  4295. var mem = null;
  4296. Tag = this.GetMemInfoInt8(sin + 8);
  4297. if (Tag === 0) {
  4298. mem = this.getModuleMemoryDataView();
  4299. TimeOut = mem.getBigInt64(sin + 24,true);
  4300. Precision = mem.getBigInt64(sin + 32,true);
  4301. msTimeOut = TimeOut / Precision;
  4302. arr = new Int32Array(this.FMemory.buffer);
  4303. Atomics.store(arr,256,0);
  4304. msTimeout32 = pas.SysUtils.StrToInt(msTimeOut.toString());
  4305. Atomics.wait(arr,256,0,msTimeout32);
  4306. };
  4307. Result = 0;
  4308. return Result;
  4309. };
  4310. this.proc_exit = function (rval) {
  4311. var Result = 0;
  4312. this.FExitCode = rval;
  4313. Result = 0;
  4314. return Result;
  4315. };
  4316. this.proc_raise = function (sig) {
  4317. var Result = 0;
  4318. console.log("Unimplemented: TPas2JSWASIEnvironment.proc_raise");
  4319. Result = 52;
  4320. return Result;
  4321. };
  4322. this.random_get = function (bufPtr, bufLen) {
  4323. var Result = 0;
  4324. var arr = null;
  4325. var I = 0;
  4326. var View = null;
  4327. arr = new Uint8Array(bufLen);
  4328. crypto.getRandomValues(arr);
  4329. View = this.getModuleMemoryDataView();
  4330. for (var $l = 0, $end = arr.length - 1; $l <= $end; $l++) {
  4331. I = $l;
  4332. View.setInt8(bufPtr + I,arr[I]);
  4333. };
  4334. Result = 0;
  4335. return Result;
  4336. };
  4337. this.sched_yield = function () {
  4338. var Result = 0;
  4339. Result = 0;
  4340. return Result;
  4341. };
  4342. this.sock_recv = function () {
  4343. var Result = 0;
  4344. console.log("Unimplemented: TPas2JSWASIEnvironment.sock_recv");
  4345. Result = 52;
  4346. return Result;
  4347. };
  4348. this.sock_send = function () {
  4349. var Result = 0;
  4350. console.log("Unimplemented: TPas2JSWASIEnvironment.sock_recv");
  4351. Result = 52;
  4352. return Result;
  4353. };
  4354. this.sock_shutdown = function () {
  4355. var Result = 0;
  4356. console.log("Unimplemented: TPas2JSWASIEnvironment.sock_shutdown");
  4357. Result = 52;
  4358. return Result;
  4359. };
  4360. this.SetMemory = function (aMemory) {
  4361. this.FMemory = aMemory;
  4362. };
  4363. this.Create$1 = function () {
  4364. var I = 0;
  4365. this.FWASIImportName = "wasi_snapshot_preview1";
  4366. this.FArguments = pas.Classes.TStringList.$create("Create$1");
  4367. this.FEnvironment = pas.Classes.TStringList.$create("Create$1");
  4368. for (var $l = 0, $end = pas.SysUtils.GetEnvironmentVariableCount() - 1; $l <= $end; $l++) {
  4369. I = $l;
  4370. this.FEnvironment.Add(pas.SysUtils.GetEnvironmentString(I));
  4371. };
  4372. return this;
  4373. };
  4374. this.Destroy = function () {
  4375. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4376. return this.p.FEnvironment;
  4377. }, set: function (v) {
  4378. this.p.FEnvironment = v;
  4379. }});
  4380. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4381. return this.p.FArguments;
  4382. }, set: function (v) {
  4383. this.p.FArguments = v;
  4384. }});
  4385. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4386. return this.p.FImportExtensions;
  4387. }, set: function (v) {
  4388. this.p.FImportExtensions = v;
  4389. }});
  4390. pas.System.TObject.Destroy.call(this);
  4391. };
  4392. this.GetUTF8StringFromMem = function (aLoc, aLen) {
  4393. var Result = "";
  4394. var tmpBuf = null;
  4395. tmpBuf = pas.JS.SharedToNonShared(this.getModuleMemoryDataView().buffer.slice(aLoc,aLoc + aLen));
  4396. Result = this.UTF8TextDecoder.decode(tmpBuf);
  4397. return Result;
  4398. };
  4399. this.GetUTF8StringFromArray = function (aSourceArray) {
  4400. var Result = "";
  4401. var TmpBytes = null;
  4402. TmpBytes = pas.JS.SharedToNonShared$1(aSourceArray,false);
  4403. Result = this.UTF8TextDecoder.decode(TmpBytes);
  4404. return Result;
  4405. };
  4406. this.SetUTF8StringInMem = function (aLoc, aLen, AString) {
  4407. var Result = 0;
  4408. var Arr = null;
  4409. Arr = this.UTF8TextEncoder.encode(AString);
  4410. if (Arr.byteLength > aLen) {
  4411. Result = -Arr.byteLength}
  4412. else if (Arr.byteLength === 0) {
  4413. Result = 0}
  4414. else Result = this.SetUTF8StringInMem$1(aLoc,aLen,Arr);
  4415. return Result;
  4416. };
  4417. this.SetUTF8StringInMem$1 = function (aLoc, aLen, AStringBuf) {
  4418. var Result = 0;
  4419. var Arr = null;
  4420. if (AStringBuf == null) return 0;
  4421. Arr = new Uint8Array(this.getModuleMemoryDataView().buffer,aLoc,aLen);
  4422. Arr.set(AStringBuf);
  4423. Result = AStringBuf.byteLength;
  4424. return Result;
  4425. };
  4426. this.SetMemInfoInt32 = function (aLoc, aValue) {
  4427. var Result = 0;
  4428. var View = null;
  4429. View = this.getModuleMemoryDataView();
  4430. View.setInt32(aLoc,aValue,true);
  4431. Result = aLoc + 4;
  4432. return Result;
  4433. };
  4434. this.SetMemInfoInt64 = function (aLoc, aValue) {
  4435. var Result = 0;
  4436. var View = null;
  4437. View = this.getModuleMemoryDataView();
  4438. this.$class.setBigInt64(View,aLoc,aValue,true);
  4439. Result = aLoc + 8;
  4440. return Result;
  4441. };
  4442. this.SetMemInfoUInt8 = function (aLoc, aValue) {
  4443. var Result = 0;
  4444. var View = null;
  4445. View = this.getModuleMemoryDataView();
  4446. View.setUint8(aLoc,aValue);
  4447. Result = aLoc + 1;
  4448. return Result;
  4449. };
  4450. this.SetMemInfoUInt32 = function (aLoc, aValue) {
  4451. var Result = 0;
  4452. var View = null;
  4453. View = this.getModuleMemoryDataView();
  4454. View.setUint32(aLoc,aValue,true);
  4455. Result = aLoc + 4;
  4456. return Result;
  4457. };
  4458. this.SetMemInfoUInt64 = function (aLoc, aValue) {
  4459. var Result = 0;
  4460. var View = null;
  4461. View = this.getModuleMemoryDataView();
  4462. this.$class.setBigUint64(View,aLoc,aValue,true);
  4463. Result = aLoc + 8;
  4464. return Result;
  4465. };
  4466. this.GetMemInfoInt8 = function (aLoc) {
  4467. var Result = 0;
  4468. var View = null;
  4469. View = this.getModuleMemoryDataView();
  4470. Result = View.getInt8(aLoc);
  4471. return Result;
  4472. };
  4473. this.GetMemInfoInt32 = function (aLoc) {
  4474. var Result = 0;
  4475. var View = null;
  4476. View = this.getModuleMemoryDataView();
  4477. Result = View.getInt32(aLoc,true);
  4478. return Result;
  4479. };
  4480. this.AddImports = function (aObject) {
  4481. var Ext = null;
  4482. var I = 0;
  4483. var O = null;
  4484. aObject[this.FWASIImportName] = this.GetImportObject();
  4485. if (this.FImportExtensions != null) for (var $l = 0, $end = this.FImportExtensions.FCount - 1; $l <= $end; $l++) {
  4486. I = $l;
  4487. Ext = rtl.getObject(this.FImportExtensions.Get(I));
  4488. O = new Object();
  4489. Ext.FillImportObject(O);
  4490. aObject[Ext.ImportName()] = O;
  4491. };
  4492. };
  4493. this.SetExports = function (aExports) {
  4494. var Ext = null;
  4495. var I = 0;
  4496. if (this.FImportExtensions != null) for (var $l = 0, $end = this.FImportExtensions.FCount - 1; $l <= $end; $l++) {
  4497. I = $l;
  4498. Ext = rtl.getObject(this.FImportExtensions.Get(I));
  4499. Ext.SetInstanceExports(aExports);
  4500. };
  4501. };
  4502. });
  4503. rtl.createClass(this,"TImportExtension",pas.System.TObject,function () {
  4504. this.$init = function () {
  4505. pas.System.TObject.$init.call(this);
  4506. this.FEnv = null;
  4507. this.FInstanceExports = null;
  4508. };
  4509. this.$final = function () {
  4510. this.FEnv = undefined;
  4511. this.FInstanceExports = undefined;
  4512. pas.System.TObject.$final.call(this);
  4513. };
  4514. this.SetInstanceExports = function (AValue) {
  4515. if (this.FInstanceExports === AValue) return;
  4516. this.FInstanceExports = AValue;
  4517. };
  4518. this.Create$1 = function (aEnv) {
  4519. this.FEnv = aEnv;
  4520. if (this.FEnv != null) this.FEnv.AddExtension(this);
  4521. return this;
  4522. };
  4523. this.Destroy = function () {
  4524. if (this.FEnv != null) this.FEnv.RemoveExtension(this);
  4525. pas.System.TObject.Destroy.call(this);
  4526. };
  4527. this.RegisterName = function () {
  4528. var Result = "";
  4529. Result = this.$classname;
  4530. return Result;
  4531. };
  4532. });
  4533. rtl.createClass(this,"TImportExtensionRegistry",pas.System.TObject,function () {
  4534. this._Instance = null;
  4535. this.$init = function () {
  4536. pas.System.TObject.$init.call(this);
  4537. this.FExtensions = [];
  4538. this.FExtensionCount = 0;
  4539. };
  4540. this.$final = function () {
  4541. this.FExtensions = undefined;
  4542. pas.System.TObject.$final.call(this);
  4543. };
  4544. this.Grow = function () {
  4545. this.FExtensions = rtl.arraySetLength(this.FExtensions,null,rtl.length(this.FExtensions) + 1);
  4546. };
  4547. this.create$1 = function () {
  4548. this.FExtensionCount = 0;
  4549. this.Grow();
  4550. return this;
  4551. };
  4552. this.Destroy = function () {
  4553. pas.System.TObject.Destroy.call(this);
  4554. };
  4555. this.GetExtensions = function () {
  4556. var Result = [];
  4557. Result = rtl.arrayCopy(0,this.FExtensions,0,this.FExtensionCount);
  4558. return Result;
  4559. };
  4560. });
  4561. rtl.recNewT(this,"TWebAssemblyStartDescriptor",function () {
  4562. this.Module = null;
  4563. this.Memory = null;
  4564. this.Table = null;
  4565. this.Exported = null;
  4566. this.Imports = null;
  4567. this.Instance = null;
  4568. this.CallRun = null;
  4569. this.RunExceptionClass = "";
  4570. this.RunExceptionMessage = "";
  4571. this.$eq = function (b) {
  4572. 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);
  4573. };
  4574. this.$assign = function (s) {
  4575. this.Module = s.Module;
  4576. this.Memory = s.Memory;
  4577. this.Table = s.Table;
  4578. this.Exported = s.Exported;
  4579. this.Imports = s.Imports;
  4580. this.Instance = s.Instance;
  4581. this.CallRun = s.CallRun;
  4582. this.RunExceptionClass = s.RunExceptionClass;
  4583. this.RunExceptionMessage = s.RunExceptionMessage;
  4584. return this;
  4585. };
  4586. });
  4587. rtl.createClass(this,"TWASIHost",pas.Classes.TComponent,function () {
  4588. this.$init = function () {
  4589. pas.Classes.TComponent.$init.call(this);
  4590. this.FAfterInstantation = null;
  4591. this.FAfterStart = null;
  4592. this.FAutoCreateExtensions = false;
  4593. this.FBeforeStart = null;
  4594. this.FConvertNativeExceptions = false;
  4595. this.FEnv = null;
  4596. this.FExcludeExtensions = null;
  4597. this.FExported = null;
  4598. this.FOnAllExtensionsCreated = null;
  4599. this.FOnExtensionCreated = null;
  4600. this.FOnWasmException = null;
  4601. this.FPreparedStartDescriptor = $mod.TWebAssemblyStartDescriptor.$new();
  4602. this.FMemoryDescriptor = pas.webassembly.TJSWebAssemblyMemoryDescriptor.$new();
  4603. this.FOnConsoleRead = null;
  4604. this.FOnConsoleWrite = null;
  4605. this.FPredefinedConsoleInput = null;
  4606. this.FReadLineCount = 0;
  4607. this.FTableDescriptor = pas.webassembly.TJSWebAssemblyTableDescriptor.$new();
  4608. this.FExtensions = [];
  4609. };
  4610. this.$final = function () {
  4611. this.FAfterInstantation = undefined;
  4612. this.FAfterStart = undefined;
  4613. this.FBeforeStart = undefined;
  4614. this.FEnv = undefined;
  4615. this.FExcludeExtensions = undefined;
  4616. this.FExported = undefined;
  4617. this.FOnAllExtensionsCreated = undefined;
  4618. this.FOnExtensionCreated = undefined;
  4619. this.FOnWasmException = undefined;
  4620. this.FPreparedStartDescriptor = undefined;
  4621. this.FMemoryDescriptor = undefined;
  4622. this.FOnConsoleRead = undefined;
  4623. this.FOnConsoleWrite = undefined;
  4624. this.FPredefinedConsoleInput = undefined;
  4625. this.FTableDescriptor = undefined;
  4626. this.FExtensions = undefined;
  4627. pas.Classes.TComponent.$final.call(this);
  4628. };
  4629. this.GetEnv = function () {
  4630. var Result = null;
  4631. if (this.FEnv === null) {
  4632. this.FEnv = this.CreateWasiEnvironment();
  4633. this.FEnv.FOnStdErrorWrite = rtl.createCallback(this,"DoStdWrite");
  4634. this.FEnv.FOnStdOutputWrite = rtl.createCallback(this,"DoStdWrite");
  4635. this.FEnv.FOnGetConsoleInputString = rtl.createCallback(this,"DoStdRead");
  4636. if (this.FAutoCreateExtensions) this.CreateStandardExtensions();
  4637. };
  4638. Result = this.FEnv;
  4639. return Result;
  4640. };
  4641. this.NeedSharedMemory = function () {
  4642. var Result = false;
  4643. Result = false;
  4644. return Result;
  4645. };
  4646. this.ConvertWasmException = function () {
  4647. var Result = false;
  4648. var lInfo = $mod.TLastExceptionInfo.$new();
  4649. lInfo.$assign($mod.TLastExceptionInfo.$new());
  4650. Result = !this.GetExceptionInfo(lInfo);
  4651. if (Result) return Result;
  4652. lInfo.doraise = true;
  4653. if (this.FOnWasmException != null) this.FOnWasmException(this,lInfo);
  4654. if (lInfo.doraise) throw $mod.EWasmNativeException.$create("create$2",[lInfo.ClassName,lInfo.Message]);
  4655. return Result;
  4656. };
  4657. this.WrapExports = function (aExported) {
  4658. var $Self = this;
  4659. var Result = null;
  4660. function createwrapper(aScope, aFunc) {
  4661. var Result = undefined;
  4662. Result = function () {
  4663. var Result = undefined;
  4664. Result = undefined;
  4665. try {
  4666. Result=aFunc.apply(aScope,arguments);
  4667. } catch ($e) {
  4668. if (rtl.isExt($e,WebAssembly.Exception)) {
  4669. var E = $e;
  4670. if ($Self.ConvertWasmException()) throw $e;
  4671. } else throw $e
  4672. };
  4673. return Result;
  4674. };
  4675. return Result;
  4676. };
  4677. var S = "";
  4678. var lFunc = undefined;
  4679. var LNew = null;
  4680. LNew = new Object();
  4681. for (var $in = Object.getOwnPropertyNames(aExported), $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  4682. S = $in[$l];
  4683. lFunc = aExported[S];
  4684. if (!rtl.isFunction(lFunc) || (S === "GetLastExceptionInfo") || (S === "FreeLastExceptionInfo")) {
  4685. LNew[S] = lFunc}
  4686. else LNew[S] = createwrapper(this,lFunc);
  4687. };
  4688. Result = LNew;
  4689. return Result;
  4690. };
  4691. this.DeleteExtensions = function () {
  4692. var I = 0;
  4693. for (var $l = 0, $end = rtl.length(this.FExtensions) - 1; $l <= $end; $l++) {
  4694. I = $l;
  4695. pas.SysUtils.FreeAndNil({a: I, p: this.FExtensions, get: function () {
  4696. return this.p[this.a];
  4697. }, set: function (v) {
  4698. this.p[this.a] = v;
  4699. }});
  4700. };
  4701. this.FExtensions = rtl.arraySetLength(this.FExtensions,null,0);
  4702. };
  4703. this.DoCreateStandardExtensions = function () {
  4704. var lCount = 0;
  4705. var lClass = null;
  4706. var lClasses = [];
  4707. this.DeleteExtensions();
  4708. lClasses = $mod.TImportExtensionRegistry._Instance.GetExtensions();
  4709. this.FExtensions = rtl.arraySetLength(this.FExtensions,null,rtl.length(lClasses));
  4710. lCount = 0;
  4711. for (var $in = lClasses, $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  4712. lClass = $in[$l];
  4713. if ((this.FExcludeExtensions.IndexOf(lClass.RegisterName()) === -1) && (this.FExcludeExtensions.IndexOf(lClass.$classname) === -1)) {
  4714. this.FExtensions[lCount] = this.CreateStandardExtension(lClass);
  4715. lCount += 1;
  4716. };
  4717. };
  4718. };
  4719. this.CreateStandardExtension = function (aClass) {
  4720. var Result = null;
  4721. Result = aClass.$create("Create");
  4722. if (this.FOnExtensionCreated != null) this.FOnExtensionCreated(this,Result);
  4723. return Result;
  4724. };
  4725. this.DoAfterInstantiate = function () {
  4726. if (this.FAfterInstantation != null) this.FAfterInstantation(this);
  4727. };
  4728. this.RunWebAssemblyInstance = function (aBeforeStart, aAfterStart, aRun) {
  4729. var Result = false;
  4730. Result = true;
  4731. if (aBeforeStart != null) Result = aBeforeStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor));
  4732. if (this.FBeforeStart != null) this.FBeforeStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor),{get: function () {
  4733. return Result;
  4734. }, set: function (v) {
  4735. Result = v;
  4736. }});
  4737. if (!Result) return Result;
  4738. try {
  4739. if (aRun === null) aRun = this.FPreparedStartDescriptor.CallRun;
  4740. aRun(this.FPreparedStartDescriptor.Exported);
  4741. if (aAfterStart != null) aAfterStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor));
  4742. if (this.FAfterStart != null) this.FAfterStart(this,$mod.TWebAssemblyStartDescriptor.$clone(this.FPreparedStartDescriptor));
  4743. } catch ($e) {
  4744. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  4745. var E = $e;
  4746. this.FPreparedStartDescriptor.RunExceptionClass = E.$classname;
  4747. this.FPreparedStartDescriptor.RunExceptionMessage = E.fMessage;
  4748. } else if (rtl.isExt($e,Error)) {
  4749. var JE = $e;
  4750. this.FPreparedStartDescriptor.RunExceptionClass = typeof(JE);
  4751. this.FPreparedStartDescriptor.RunExceptionMessage = JE.message;
  4752. } else if (rtl.isExt($e,Object)) {
  4753. var OE = $e;
  4754. this.FPreparedStartDescriptor.RunExceptionClass = typeof(OE);
  4755. this.FPreparedStartDescriptor.RunExceptionMessage = JSON.stringify(OE);
  4756. } else throw $e
  4757. };
  4758. if (this.FPreparedStartDescriptor.RunExceptionClass !== "") console.error("Running Webassembly resulted in exception. Exception class: ",this.FPreparedStartDescriptor.RunExceptionClass,", message:",this.FPreparedStartDescriptor.RunExceptionMessage);
  4759. return Result;
  4760. };
  4761. this.DoStdRead = function (Sender, AInput) {
  4762. var S = "";
  4763. S = "";
  4764. if (this.FOnConsoleRead != null) {
  4765. this.FOnConsoleRead(this,{get: function () {
  4766. return S;
  4767. }, set: function (v) {
  4768. S = v;
  4769. }})}
  4770. else {
  4771. if (this.FReadLineCount < this.FPredefinedConsoleInput.GetCount()) {
  4772. S = this.FPredefinedConsoleInput.Get(this.FReadLineCount);
  4773. this.FReadLineCount += 1;
  4774. };
  4775. };
  4776. AInput.set(S);
  4777. };
  4778. this.DoStdWrite = function (Sender, aOutput) {
  4779. this.WriteOutput(aOutput);
  4780. };
  4781. this.CreateWasiEnvironment = function () {
  4782. var Result = null;
  4783. Result = $mod.TPas2JSWASIEnvironment.$create("Create$1");
  4784. return Result;
  4785. };
  4786. this.Create$1 = function (aOwner) {
  4787. pas.Classes.TComponent.Create$1.call(this,aOwner);
  4788. this.FMemoryDescriptor.initial = 256;
  4789. this.FMemoryDescriptor.maximum = 256;
  4790. this.FMemoryDescriptor.shared = this.$class.NeedSharedMemory();
  4791. this.FTableDescriptor.initial = 0;
  4792. this.FTableDescriptor.maximum = 0;
  4793. this.FTableDescriptor.element = "anyfunc";
  4794. this.FPredefinedConsoleInput = pas.Classes.TStringList.$create("Create$1");
  4795. this.FExcludeExtensions = pas.Classes.TStringList.$create("Create$1");
  4796. this.FConvertNativeExceptions = true;
  4797. return this;
  4798. };
  4799. this.Destroy = function () {
  4800. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4801. return this.p.FExcludeExtensions;
  4802. }, set: function (v) {
  4803. this.p.FExcludeExtensions = v;
  4804. }});
  4805. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4806. return this.p.FPredefinedConsoleInput;
  4807. }, set: function (v) {
  4808. this.p.FPredefinedConsoleInput = v;
  4809. }});
  4810. pas.SysUtils.FreeAndNil({p: this, get: function () {
  4811. return this.p.FEnv;
  4812. }, set: function (v) {
  4813. this.p.FEnv = v;
  4814. }});
  4815. pas.Classes.TComponent.Destroy.call(this);
  4816. };
  4817. this.CreateStandardExtensions = function () {
  4818. this.DoCreateStandardExtensions();
  4819. if (this.FOnAllExtensionsCreated != null) this.FOnAllExtensionsCreated(this);
  4820. };
  4821. this.GetExceptionInfo = function (aInfo) {
  4822. var Result = false;
  4823. var lPtr = 0;
  4824. var lPointer = 0;
  4825. var lString = 0;
  4826. var lLen = 0;
  4827. var lVal = undefined;
  4828. var lVal2 = undefined;
  4829. Result = false;
  4830. lVal = this.FExported["GetLastExceptionInfo"];
  4831. lVal2 = this.FExported["FreeLastExceptionInfo"];
  4832. if (!(pas.JS.isDefined(lVal) && pas.JS.isDefined(lVal2))) return Result;
  4833. lPointer = lVal();
  4834. if (lPointer === 0) return Result;
  4835. lPtr = lPointer;
  4836. lString = this.GetEnv().GetMemInfoInt32(lPtr);
  4837. lPtr += 4;
  4838. lLen = this.GetEnv().GetMemInfoInt32(lPtr);
  4839. lPtr += 4;
  4840. aInfo.ClassName = this.GetEnv().GetUTF8StringFromMem(lString,lLen);
  4841. lString = this.GetEnv().GetMemInfoInt32(lPtr);
  4842. lPtr += 4;
  4843. lLen = this.GetEnv().GetMemInfoInt32(lPtr);
  4844. lPtr += 4;
  4845. aInfo.Message = this.GetEnv().GetUTF8StringFromMem(lString,lLen);
  4846. aInfo.more = this.GetEnv().GetMemInfoInt8(lPtr) !== 0;
  4847. lVal2(lPointer);
  4848. Result = true;
  4849. return Result;
  4850. };
  4851. this.WriteOutput = function (aOutput) {
  4852. if (this.FOnConsoleWrite != null) {
  4853. this.FOnConsoleWrite(this,aOutput)}
  4854. else pas.System.Writeln(aOutput);
  4855. };
  4856. this.PrepareWebAssemblyInstance = function (aDescr) {
  4857. if (this.FConvertNativeExceptions) aDescr.Exported = this.WrapExports(aDescr.Exported);
  4858. this.FPreparedStartDescriptor.$assign(aDescr);
  4859. this.FExported = this.FPreparedStartDescriptor.Exported;
  4860. this.GetEnv().SetInstance(aDescr.Instance);
  4861. this.GetEnv().SetMemory(aDescr.Memory);
  4862. this.GetEnv().SetExports(this.FExported);
  4863. this.DoAfterInstantiate();
  4864. };
  4865. this.InitStartDescriptor = function (aMemory, aTable, aImportObj) {
  4866. var Result = $mod.TWebAssemblyStartDescriptor.$new();
  4867. Result.Memory = aMemory;
  4868. Result.Table = aTable;
  4869. if (!(aImportObj != null)) aImportObj = new Object();
  4870. aImportObj["env"] = pas.JS.New(["memory",Result.Memory,"tbl",Result.Table]);
  4871. this.GetEnv().AddImports(aImportObj);
  4872. Result.Imports = aImportObj;
  4873. return Result;
  4874. };
  4875. });
  4876. $mod.$implcode = function () {
  4877. $impl.toUTF8Array = function (str) {
  4878. var Result = null;
  4879. var Len = 0;
  4880. var I = 0;
  4881. var P = 0;
  4882. var charCode = 0;
  4883. function push(abyte) {
  4884. Result[P] = abyte;
  4885. P += 1;
  4886. };
  4887. Result = new Uint8Array(str.length * 4);
  4888. P = 0;
  4889. Len = str.length;
  4890. I = 1;
  4891. while (I <= Len) {
  4892. charCode = str.charCodeAt(I - 1);
  4893. if (charCode < 0x80) {
  4894. push(charCode)}
  4895. else if (charCode < 0x800) {
  4896. push(rtl.or(0xc0,Math.floor(charCode / 64)));
  4897. push(rtl.or(0x80,charCode & 0x3f));
  4898. } else if ((charCode < 0xd800) || (charCode >= 0xe000)) {
  4899. push(rtl.or(0xe0,Math.floor(charCode / 4096)));
  4900. push(rtl.or(0x80,Math.floor(charCode / 64) & 0x3f));
  4901. push(rtl.or(0x80,charCode & 0x3f));
  4902. } else {
  4903. I += 1;
  4904. charCode = 0x10000 + rtl.or(rtl.shl(charCode & 0x3ff,10),str.charCodeAt(I - 1) & 0x3ff);
  4905. push(rtl.or(0xf0,Math.floor(charCode / 262144)));
  4906. push(rtl.or(0x80,Math.floor(charCode / 4096) & 0x3f));
  4907. push(rtl.or(0x80,Math.floor(charCode / 64) & 0x3f));
  4908. push(rtl.or(0x80,charCode & 0x3f));
  4909. };
  4910. I += 1;
  4911. };
  4912. Result = Result.slice(0,P);
  4913. return Result;
  4914. };
  4915. };
  4916. $mod.$init = function () {
  4917. (function () {
  4918. var Opts = null;
  4919. Opts = new Object();
  4920. Opts.ignoreBOM = true;
  4921. Opts.fatal = true;
  4922. $mod.TPas2JSWASIEnvironment.UTF8TextDecoder = new TextDecoder("utf-8",Opts);
  4923. $mod.TPas2JSWASIEnvironment.UTF8TextEncoder = new TextEncoder();
  4924. })();
  4925. (function () {
  4926. $mod.TImportExtensionRegistry._Instance = $mod.TImportExtensionRegistry.$create("create$1");
  4927. })();
  4928. };
  4929. },["weborworker"]);
  4930. rtl.module("Rtl.WorkerCommands",["System","SysUtils","JS","weborworker"],function () {
  4931. "use strict";
  4932. var $mod = this;
  4933. this.cmdConsole = "console";
  4934. this.cmdException = "exception";
  4935. this.channelConsole = "console_output";
  4936. this.cFldCommand = "command";
  4937. rtl.createClass(this,"EWorkerCommand",pas.SysUtils.Exception,function () {
  4938. });
  4939. rtl.createHelper(this,"TCustomWorkerCommandHelper",null,function () {
  4940. this.createCommand = function (aCommand, aSenderID) {
  4941. var Result = null;
  4942. Result = new Object();
  4943. Result.canceled = false;
  4944. Result.command = aCommand;
  4945. Result.senderId = aSenderID;
  4946. return Result;
  4947. };
  4948. });
  4949. rtl.createHelper(this,"TConsoleOutputCommandHelper",this.TCustomWorkerCommandHelper,function () {
  4950. this.create = function (aMessage) {
  4951. var Result = null;
  4952. Result = $mod.TCustomWorkerCommandHelper.createCommand($mod.cmdConsole,"");
  4953. Result.ConsoleMessage = aMessage;
  4954. return Result;
  4955. };
  4956. });
  4957. rtl.createHelper(this,"TWorkerExceptionCommandHelper",this.TCustomWorkerCommandHelper,function () {
  4958. this.Create = function (aExceptionClass, aExceptionMessage, aThreadID) {
  4959. var Result = null;
  4960. Result = $mod.TCustomWorkerCommandHelper.createCommand($mod.cmdException,pas.SysUtils.IntToStr(aThreadID));
  4961. Result.ExceptionClass = aExceptionClass;
  4962. Result.ExceptionMessage = aExceptionMessage;
  4963. return Result;
  4964. };
  4965. });
  4966. rtl.createClass(this,"TCommandDispatcher",pas.System.TObject,function () {
  4967. rtl.recNewT(this,"TCommandHandlerReg",function () {
  4968. this.SingleHandler = false;
  4969. this.$new = function () {
  4970. var r = Object.create(this);
  4971. r.Handlers = [];
  4972. return r;
  4973. };
  4974. this.$eq = function (b) {
  4975. return (this.Handlers === b.Handlers) && (this.SingleHandler === b.SingleHandler);
  4976. };
  4977. this.$assign = function (s) {
  4978. this.Handlers = rtl.arrayRef(s.Handlers);
  4979. this.SingleHandler = s.SingleHandler;
  4980. return this;
  4981. };
  4982. });
  4983. rtl.recNewT(this,"TJSWorkerReg",function () {
  4984. this.Worker = null;
  4985. this.Name = "";
  4986. this.$eq = function (b) {
  4987. return (this.Worker === b.Worker) && (this.Name === b.Name);
  4988. };
  4989. this.$assign = function (s) {
  4990. this.Worker = s.Worker;
  4991. this.Name = s.Name;
  4992. return this;
  4993. };
  4994. });
  4995. this._Instance = null;
  4996. this._DispatcherClass = null;
  4997. this.$init = function () {
  4998. pas.System.TObject.$init.call(this);
  4999. this.FDefaultSenderID = "";
  5000. this.FMap = null;
  5001. this.FWorkers = [];
  5002. this.FConsoleChannel = null;
  5003. };
  5004. this.$final = function () {
  5005. this.FMap = undefined;
  5006. this.FWorkers = undefined;
  5007. this.FConsoleChannel = undefined;
  5008. pas.System.TObject.$final.call(this);
  5009. };
  5010. this.GetInstance = function () {
  5011. var Result = null;
  5012. var C = null;
  5013. if (!($mod.TCommandDispatcher._Instance != null)) {
  5014. C = $mod.TCommandDispatcher._DispatcherClass;
  5015. if (C === null) C = $mod.TCommandDispatcher;
  5016. $mod.TCommandDispatcher._Instance = C.$create("create$1");
  5017. };
  5018. Result = $mod.TCommandDispatcher._Instance;
  5019. return Result;
  5020. };
  5021. this.IsCommandEvent = function (aEvent) {
  5022. var Result = false;
  5023. var Obj = null;
  5024. Result = (aEvent != null) && rtl.isObject(aEvent.data);
  5025. if (Result) {
  5026. Obj = aEvent.data;
  5027. Result = Obj.hasOwnProperty($mod.cFldCommand) && rtl.isString(Obj[$mod.cFldCommand]);
  5028. };
  5029. return Result;
  5030. };
  5031. this.CheckSenderID = function (aCommand) {
  5032. if (aCommand.senderId === "") aCommand.senderId = this.FDefaultSenderID;
  5033. };
  5034. this.IndexOfWorker = function (aWorker) {
  5035. var Result = 0;
  5036. Result = rtl.length(this.FWorkers) - 1;
  5037. while ((Result >= 0) && (this.FWorkers[Result].Worker !== aWorker)) Result -= 1;
  5038. return Result;
  5039. };
  5040. this.IndexOfWorker$1 = function (aName) {
  5041. var Result = 0;
  5042. Result = rtl.length(this.FWorkers) - 1;
  5043. while ((Result >= 0) && (this.FWorkers[Result].Name !== aName)) Result -= 1;
  5044. return Result;
  5045. };
  5046. this.HandleIncomingMessage = function (aEvent) {
  5047. var lCommand = null;
  5048. if (this.$class.IsCommandEvent(aEvent)) {
  5049. lCommand = aEvent.data;
  5050. lCommand._sender = aEvent.target;
  5051. this.HandleCommand(lCommand);
  5052. };
  5053. };
  5054. this.HandleCommand = function (aCommand) {
  5055. var lCmd = "";
  5056. var lValue = undefined;
  5057. var lHandler = null;
  5058. lCmd = aCommand.command;
  5059. lValue = this.FMap.get(lCmd);
  5060. if (pas.System.Assigned(lValue)) for (var $in = lValue.Handlers, $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  5061. lHandler = $in[$l];
  5062. lHandler(aCommand);
  5063. if (aCommand.canceled) break;
  5064. };
  5065. };
  5066. this.create$1 = function () {
  5067. this.FMap = new Map();
  5068. this.FConsoleChannel = new BroadcastChannel($mod.channelConsole);
  5069. if (pas.weborworker.isMainBrowserThread()) {
  5070. this.FConsoleChannel.addEventListener("message",rtl.createSafeCallback(this,"HandleIncomingMessage"))}
  5071. else self.addEventListener("message",rtl.createSafeCallback(this,"HandleIncomingMessage"));
  5072. return this;
  5073. };
  5074. this.Destroy = function () {
  5075. this.FConsoleChannel.close();
  5076. this.FConsoleChannel = null;
  5077. pas.System.TObject.Destroy.call(this);
  5078. };
  5079. this.SendCommand = function (aWorker, aCommand) {
  5080. this.CheckSenderID(aCommand);
  5081. aWorker.postMessage(aCommand);
  5082. };
  5083. this.SendCommand$2 = function (aCommand) {
  5084. if (!(pas.weborworker.isWebWorker() || pas.weborworker.IsServiceWorker())) throw $mod.EWorkerCommand.$create("Create$1",["Cannot send to starting thread from main page"]);
  5085. this.CheckSenderID(aCommand);
  5086. self.postMessage(aCommand);
  5087. };
  5088. this.SendConsoleCommand = function (aCommand) {
  5089. if (!(pas.weborworker.isWebWorker() || pas.weborworker.IsServiceWorker())) throw $mod.EWorkerCommand.$create("Create$1",["Cannot send to starting thread from main page"]);
  5090. this.CheckSenderID(aCommand);
  5091. this.FConsoleChannel.postMessage(aCommand);
  5092. };
  5093. this.RegisterCommandHandler = function (aCommand, aHandler, IsSingle) {
  5094. var lValue = undefined;
  5095. var lNewReg = this.TCommandHandlerReg.$new();
  5096. lValue = this.FMap.get(aCommand);
  5097. if (pas.System.Assigned(lValue)) {
  5098. if (!(lValue.SingleHandler || IsSingle)) {
  5099. lValue.Handlers.push(aHandler)}
  5100. else {
  5101. if (rtl.length(lValue.Handlers) > 0) throw $mod.EWorkerCommand.$create("CreateFmt",["There is already a handler for command %s",pas.System.VarRecs(18,aCommand)]);
  5102. lValue.Handlers = [aHandler];
  5103. lValue.SingleHandler = IsSingle;
  5104. };
  5105. } else {
  5106. lNewReg.$assign(this.TCommandHandlerReg.$new());
  5107. lNewReg.Handlers = [aHandler];
  5108. lNewReg.SingleHandler = IsSingle;
  5109. this.FMap.set(aCommand,this.TCommandHandlerReg.$clone(lNewReg));
  5110. };
  5111. };
  5112. this.RegisterWorker = function (aWorker, aName) {
  5113. var lReg = this.TJSWorkerReg.$new();
  5114. if (this.IndexOfWorker$1(aName) >= 0) throw $mod.EWorkerCommand.$create("CreateFmt",["Duplicate worker name: %s",pas.System.VarRecs(18,aName)]);
  5115. if (this.IndexOfWorker(aWorker) >= 0) throw $mod.EWorkerCommand.$create("Create$1",["Duplicate worker instance"]);
  5116. lReg.Worker = aWorker;
  5117. lReg.Name = aName;
  5118. this.FWorkers = rtl.arrayPush(this.TJSWorkerReg,this.FWorkers,this.TJSWorkerReg.$clone(lReg));
  5119. aWorker.addEventListener("message",rtl.createSafeCallback(this,"HandleIncomingMessage"));
  5120. };
  5121. });
  5122. });
  5123. rtl.module("Rtl.WebThreads",["System","JS","SysUtils","wasienv","webassembly","Rtl.WorkerCommands"],function () {
  5124. "use strict";
  5125. var $mod = this;
  5126. this.cmdConsole = "console";
  5127. this.cmdCleanup = "cleanup";
  5128. this.cmdCancel = "cancel";
  5129. this.cmdLoaded = "loaded";
  5130. this.cmdKill = "kill";
  5131. this.cmdSpawn = "spawn";
  5132. this.cmdLoad = "load";
  5133. this.cmdRun = "run";
  5134. this.cmdReady = "ready";
  5135. this.DefaultThreadWorker = "pas2jsthreadworker.js";
  5136. this.DefaultThreadCount = 2;
  5137. this.DefaultMaxWorkerCount = 100;
  5138. this.DefaultThreadEntryPoint = "wasi_thread_start";
  5139. this.sThreadSpawn = "thread-spawn";
  5140. this.sThreadSelf = "thread_self";
  5141. rtl.createClass(this,"EWasmThreads",pas.SysUtils.Exception,function () {
  5142. });
  5143. rtl.createHelper(this,"TWorkerCommandHelper",pas["Rtl.WorkerCommands"].TCustomWorkerCommandHelper,function () {
  5144. this.NewWorker = function (aCommand, aThreadID) {
  5145. var Result = null;
  5146. if (aThreadID === -1) {
  5147. Result = pas["Rtl.WorkerCommands"].TCustomWorkerCommandHelper.createCommand(aCommand,"")}
  5148. else {
  5149. Result = pas["Rtl.WorkerCommands"].TCustomWorkerCommandHelper.createCommand(aCommand,"Wasm thread " + pas.SysUtils.IntToStr(aThreadID));
  5150. Result.ThreadID = aThreadID;
  5151. };
  5152. return Result;
  5153. };
  5154. });
  5155. rtl.createHelper(this,"TWorkerCleanupCommandHelper",this.TWorkerCommandHelper,function () {
  5156. this.CommandName = function () {
  5157. var Result = "";
  5158. Result = $mod.cmdCleanup;
  5159. return Result;
  5160. };
  5161. this.Create = function (aThreadID, aExitStatus) {
  5162. var Result = null;
  5163. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerCleanupCommandHelper.CommandName(),aThreadID);
  5164. Result.exitstatus = aExitStatus;
  5165. return Result;
  5166. };
  5167. });
  5168. rtl.createHelper(this,"TWorkerReadyCommandHelper",this.TWorkerCommandHelper,function () {
  5169. this.CommandName = function () {
  5170. var Result = "";
  5171. Result = $mod.cmdReady;
  5172. return Result;
  5173. };
  5174. this.Create = function () {
  5175. var Result = null;
  5176. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerReadyCommandHelper.CommandName(),-1);
  5177. return Result;
  5178. };
  5179. });
  5180. rtl.createHelper(this,"TWorkerLoadedCommandHelper",this.TWorkerCommandHelper,function () {
  5181. this.CommandName = function () {
  5182. var Result = "";
  5183. Result = $mod.cmdLoaded;
  5184. return Result;
  5185. };
  5186. this.Create = function () {
  5187. var Result = null;
  5188. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerLoadedCommandHelper.CommandName(),-1);
  5189. return Result;
  5190. };
  5191. });
  5192. rtl.createHelper(this,"TWorkerSpawnThreadCommandHelper",this.TWorkerCommandHelper,function () {
  5193. this.CommandName = function () {
  5194. var Result = "";
  5195. Result = $mod.cmdSpawn;
  5196. return Result;
  5197. };
  5198. this.Create = function (aThreadID, aArgs) {
  5199. var Result = null;
  5200. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerSpawnThreadCommandHelper.CommandName(),aThreadID);
  5201. Result.Arguments = aArgs;
  5202. return Result;
  5203. };
  5204. });
  5205. rtl.createHelper(this,"TWorkerLoadCommandHelper",this.TWorkerCommandHelper,function () {
  5206. this.CommandName = function () {
  5207. var Result = "";
  5208. Result = $mod.cmdLoad;
  5209. return Result;
  5210. };
  5211. this.Create = function (aModule, aMemory) {
  5212. var Result = null;
  5213. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerLoadCommandHelper.CommandName(),-1);
  5214. Result.Memory = aMemory;
  5215. Result.Module = aModule;
  5216. return Result;
  5217. };
  5218. });
  5219. rtl.createHelper(this,"TWorkerRunCommandHelper",this.TWorkerCommandHelper,function () {
  5220. this.CommandName = function () {
  5221. var Result = "";
  5222. Result = $mod.cmdRun;
  5223. return Result;
  5224. };
  5225. this.Create = function (aThreadID, aArgs) {
  5226. var Result = null;
  5227. Result = $mod.TWorkerCommandHelper.NewWorker($mod.TWorkerRunCommandHelper.CommandName(),-1);
  5228. Result.ThreadID = aThreadID;
  5229. Result.Args = aArgs;
  5230. return Result;
  5231. };
  5232. });
  5233. rtl.recNewT(this,"TThreadinfo",function () {
  5234. this.OriginThreadID = 0;
  5235. this.ThreadID = 0;
  5236. this.Arguments = 0;
  5237. this.$eq = function (b) {
  5238. return (this.OriginThreadID === b.OriginThreadID) && (this.ThreadID === b.ThreadID) && (this.Arguments === b.Arguments);
  5239. };
  5240. this.$assign = function (s) {
  5241. this.OriginThreadID = s.OriginThreadID;
  5242. this.ThreadID = s.ThreadID;
  5243. this.Arguments = s.Arguments;
  5244. return this;
  5245. };
  5246. });
  5247. rtl.createClass(this,"TWasmThreadController",pas.System.TObject,function () {
  5248. this._instanceClass = null;
  5249. this._instance = null;
  5250. this.$init = function () {
  5251. pas.System.TObject.$init.call(this);
  5252. this.FLogAPI = false;
  5253. this.FModule = null;
  5254. this.FMemory = null;
  5255. this.FOnLog = null;
  5256. };
  5257. this.$final = function () {
  5258. this.FModule = undefined;
  5259. this.FMemory = undefined;
  5260. this.FOnLog = undefined;
  5261. pas.System.TObject.$final.call(this);
  5262. };
  5263. this.GetInstance = function () {
  5264. var Result = null;
  5265. if ($mod.TWasmThreadController._instance === null) {
  5266. if ($mod.TWasmThreadController._instanceClass === null) throw $mod.EWasmThreads.$create("Create$1",["No instance class, please include Rtl.ThreadController or Rtl.ThreadWorker unit"]);
  5267. $mod.TWasmThreadController._instance = $mod.TWasmThreadController._instanceClass.$create("create$1");
  5268. };
  5269. Result = $mod.TWasmThreadController._instance;
  5270. return Result;
  5271. };
  5272. this.DoLog = function (msg) {
  5273. if (this.FLogAPI) if (this.FOnLog != null) {
  5274. this.FOnLog(msg)}
  5275. else pas.System.Writeln(msg);
  5276. };
  5277. this.DoLog$1 = function (Fmt, args) {
  5278. this.DoLog(pas.SysUtils.Format(Fmt,args));
  5279. };
  5280. this.create$1 = function () {
  5281. return this;
  5282. };
  5283. this.SetWasmModuleAndMemory = function (aModule, aMemory) {
  5284. this.FModule = aModule;
  5285. this.FMemory = aMemory;
  5286. if ((this.FModule != null) && (this.FMemory != null)) this.HaveWebassembly();
  5287. };
  5288. this.SetInstanceClass = function (aClass) {
  5289. $mod.TWasmThreadController._instanceClass = aClass;
  5290. };
  5291. });
  5292. rtl.createClass(this,"TWasmThreadSupportApi",pas.wasienv.TImportExtension,function () {
  5293. this.thread_spawn = function (start_arg) {
  5294. var Result = 0;
  5295. Result = this.ThreadController().SpawnThread(start_arg);
  5296. return Result;
  5297. };
  5298. this.thread_self = function () {
  5299. var Result = 0;
  5300. var F = null;
  5301. F = this.FInstanceExports["GetSelfThread"];
  5302. if (F != null) {
  5303. Result = F()}
  5304. else Result = 0;
  5305. return Result;
  5306. };
  5307. this.ThreadController = function () {
  5308. var Result = null;
  5309. Result = $mod.TWasmThreadController.GetInstance();
  5310. return Result;
  5311. };
  5312. this.ImportName = function () {
  5313. var Result = "";
  5314. Result = "wasi";
  5315. return Result;
  5316. };
  5317. this.FillImportObject = function (aObject) {
  5318. aObject[$mod.sThreadSpawn] = rtl.createCallback(this,"thread_spawn");
  5319. aObject[$mod.sThreadSelf] = rtl.createCallback(this,"thread_self");
  5320. };
  5321. });
  5322. });
  5323. rtl.module("Rtl.threadcontroller",["System","JS","SysUtils","Rtl.WorkerCommands","Rtl.WebThreads","weborworker"],function () {
  5324. "use strict";
  5325. var $mod = this;
  5326. var $impl = $mod.$impl;
  5327. this.TThreadWorkerState = {"0": "twsInit", twsInit: 0, "1": "twsReady", twsReady: 1, "2": "twsLoadSent", twsLoadSent: 2, "3": "twsIdle", twsIdle: 3, "4": "twsExecuting", twsExecuting: 4};
  5328. rtl.createHelper(this,"TWasmThreadHelper",null,function () {
  5329. this.GetThreadID = function () {
  5330. var Result = 0;
  5331. Result = $mod.TWasmThreadHelper.GetThreadInfo.call(this).ThreadID;
  5332. return Result;
  5333. };
  5334. this.GetThreadInfo = function () {
  5335. var Result = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5336. var S = undefined;
  5337. S = this["FThreadInfo"];
  5338. if (rtl.isObject(S)) {
  5339. Result.$assign(rtl.getObject(S))}
  5340. else Result.$assign(pas["Rtl.WebThreads"].TThreadinfo.$new());
  5341. return Result;
  5342. };
  5343. this.GetWorkerState = function () {
  5344. var Result = 0;
  5345. var S = undefined;
  5346. S = this["FState"];
  5347. if (rtl.isNumber(S)) {
  5348. Result = rtl.trunc(S)}
  5349. else Result = 0;
  5350. return Result;
  5351. };
  5352. this.SetThreadID = function (AValue) {
  5353. $mod.TWasmThreadHelper.GetThreadInfo.call(this).ThreadID = AValue;
  5354. };
  5355. this.SetThreadInfo = function (AValue) {
  5356. this["FThreadInfo"] = AValue;
  5357. };
  5358. this.SetWorkerState = function (AValue) {
  5359. this["FState"] = AValue;
  5360. };
  5361. this.Create = function (aScript) {
  5362. var Result = null;
  5363. Result = new Worker(aScript);
  5364. $mod.TWasmThreadHelper.SetThreadID.call(Result,-1);
  5365. $mod.TWasmThreadHelper.SetWorkerState.call(Result,0);
  5366. $mod.TWasmThreadHelper.SetThreadInfo.call(Result,pas["Rtl.WebThreads"].TThreadinfo.$new());
  5367. return Result;
  5368. };
  5369. this.SendCommand = function (aCommand) {
  5370. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand(this,aCommand);
  5371. };
  5372. });
  5373. rtl.createClass(this,"TThreadController",pas["Rtl.WebThreads"].TWasmThreadController,function () {
  5374. this.$init = function () {
  5375. pas["Rtl.WebThreads"].TWasmThreadController.$init.call(this);
  5376. this.FHandleConsoleMessages = false;
  5377. this.FLogAPI$1 = false;
  5378. this.FOnConsoleWrite = null;
  5379. this.FWorkerCount = 0;
  5380. this.FInitialWorkerCount = 0;
  5381. this.FMaxWorkerCount = 0;
  5382. this.FOnAllocateWorker = null;
  5383. this.FWorkerScript = "";
  5384. this.FIdleWorkers = [];
  5385. this.FBusyWorkers = [];
  5386. this.FThreads = null;
  5387. };
  5388. this.$final = function () {
  5389. this.FOnConsoleWrite = undefined;
  5390. this.FOnAllocateWorker = undefined;
  5391. this.FIdleWorkers = undefined;
  5392. this.FBusyWorkers = undefined;
  5393. this.FThreads = undefined;
  5394. pas["Rtl.WebThreads"].TWasmThreadController.$final.call(this);
  5395. };
  5396. this.HandleRawCleanupCommand = function (aCommand) {
  5397. var lWorker = null;
  5398. lWorker = aCommand._sender;
  5399. this.HandleCleanupCommand(lWorker,aCommand);
  5400. };
  5401. this.HandleRawReadyCommand = function (aCommand) {
  5402. var lWorker = null;
  5403. pas.System.Writeln("Had ready command");
  5404. lWorker = aCommand._sender;
  5405. this.HandleReadyCommand(lWorker,aCommand);
  5406. };
  5407. this.HandleRawSpawnCommand = function (aCommand) {
  5408. var lWorker = null;
  5409. lWorker = aCommand._sender;
  5410. this.HandleSpawnCommand(lWorker,aCommand);
  5411. };
  5412. this.HandleRawLoadedCommand = function (aCommand) {
  5413. var lWorker = null;
  5414. pas.System.Writeln("Receiving loaded command");
  5415. lWorker = aCommand._sender;
  5416. this.HandleLoadedCommand(lWorker,aCommand);
  5417. };
  5418. this.HandleRawConsoleCommand = function (aCommand) {
  5419. var lWorker = null;
  5420. lWorker = aCommand._sender;
  5421. this.HandleConsoleCommand(lWorker,aCommand);
  5422. };
  5423. this.HandleRawKillCommand = function (aCommand) {
  5424. var lWorker = null;
  5425. lWorker = aCommand._sender;
  5426. this.HandleKillCommand(lWorker,aCommand);
  5427. };
  5428. this.HandleRawCancelCommand = function (aCommand) {
  5429. var lWorker = null;
  5430. lWorker = aCommand._sender;
  5431. this.HandleCancelCommand(lWorker,aCommand);
  5432. };
  5433. this.HaveWebassembly = function () {
  5434. this.SendLoadCommands();
  5435. };
  5436. this.DoError = function (msg) {
  5437. this.DoLog("Error: " + msg);
  5438. };
  5439. this.AllocateNewWorker = function (aWorkerScript) {
  5440. var Result = null;
  5441. var lWorkerUrl = "";
  5442. this.DoLog("Allocating new worker for: " + aWorkerScript);
  5443. this.FWorkerCount += 1;
  5444. lWorkerUrl = aWorkerScript;
  5445. if (pas.System.Pos("?",lWorkerUrl) > 0) {
  5446. lWorkerUrl = lWorkerUrl + "&"}
  5447. else lWorkerUrl = lWorkerUrl + "?";
  5448. lWorkerUrl = lWorkerUrl + "worker=" + pas.SysUtils.IntToStr(this.FWorkerCount);
  5449. Result = $mod.TWasmThreadHelper.Create(lWorkerUrl);
  5450. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterWorker(Result,"threadworker" + pas.SysUtils.IntToStr(this.FWorkerCount));
  5451. if (this.FLogAPI$1) this.DoLog("Host not set, delaying sending load command to: " + aWorkerScript);
  5452. if (this.FOnAllocateWorker != null) this.FOnAllocateWorker(this,Result);
  5453. return Result;
  5454. };
  5455. this.SendLoadCommand = function (aThreadWorker) {
  5456. var WLC = null;
  5457. pas.System.Writeln("Sending load command to worker.");
  5458. WLC = pas["Rtl.WebThreads"].TWorkerLoadCommandHelper.Create(this.FModule,this.FMemory);
  5459. $mod.TWasmThreadHelper.SendCommand.call(aThreadWorker,WLC);
  5460. $mod.TWasmThreadHelper.SetWorkerState.call(aThreadWorker,2);
  5461. };
  5462. this.GetNewWorker = function () {
  5463. var Result = null;
  5464. var WT = null;
  5465. if (rtl.length(this.FIdleWorkers) === 0) {
  5466. if (this.FLogAPI$1) this.DoLog("No idle workers, creating new one");
  5467. if (rtl.length(this.FBusyWorkers) < this.FMaxWorkerCount) {
  5468. WT = this.AllocateNewWorker(this.FWorkerScript)}
  5469. else throw pas["Rtl.WebThreads"].EWasmThreads.$create("Create$1",[rtl.getResStr($mod,"SErrMaxWorkersReached")]);
  5470. } else {
  5471. WT = this.FIdleWorkers.pop();
  5472. };
  5473. this.FBusyWorkers.push(WT);
  5474. Result = WT;
  5475. return Result;
  5476. };
  5477. this.SpawnThread$1 = function (aInfo) {
  5478. var Result = 0;
  5479. var WT = null;
  5480. if (this.FWorkerCount === 0) this.AllocateInitialworkers();
  5481. this.DoLog$1("Enter SpawnThread for ID %d",pas.System.VarRecs(0,aInfo.ThreadID));
  5482. WT = this.GetNewWorker();
  5483. if (WT === null) {
  5484. this.DoError("Error: no worker !");
  5485. return -1;
  5486. };
  5487. $mod.TWasmThreadHelper.SetThreadInfo.call(WT,aInfo);
  5488. this.FThreads[aInfo.ThreadID] = WT;
  5489. this.SendRunCommand(WT);
  5490. Result = aInfo.ThreadID;
  5491. this.DoLog$1("Exit: SpawnThread for ID %d",pas.System.VarRecs(0,$mod.TWasmThreadHelper.GetThreadID.call(WT)));
  5492. return Result;
  5493. };
  5494. this.SendRunCommand = function (aThreadWorker) {
  5495. var WRC = null;
  5496. var $with = $mod.TWasmThreadHelper.GetThreadInfo.call(aThreadWorker);
  5497. WRC = pas["Rtl.WebThreads"].TWorkerRunCommandHelper.Create($with.ThreadID,$with.Arguments);
  5498. $mod.TWasmThreadHelper.SendCommand.call(aThreadWorker,WRC);
  5499. };
  5500. this.HandleSpawnCommand = function (aWorker, aCommand) {
  5501. var aInfo = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5502. aInfo.OriginThreadID = $mod.TWasmThreadHelper.GetThreadID.call(aWorker);
  5503. aInfo.ThreadID = aCommand.ThreadID;
  5504. aInfo.Arguments = aCommand.Arguments;
  5505. this.SpawnThread$1(pas["Rtl.WebThreads"].TThreadinfo.$clone(aInfo));
  5506. };
  5507. this.HandleReadyCommand = function (aWorker, aCommand) {
  5508. $mod.TWasmThreadHelper.SetWorkerState.call(aWorker,1);
  5509. if ((this.FMemory != null) && (this.FModule != null)) this.SendLoadCommand(aWorker);
  5510. };
  5511. this.HandleCancelCommand = function (aWorker, aCommand) {
  5512. if ((aWorker !== null) && (aCommand !== null)) ;
  5513. };
  5514. this.HandleCleanupCommand = function (aWorker, aCommand) {
  5515. var Idx = 0;
  5516. $mod.TWasmThreadHelper.SetThreadInfo.call(aWorker,pas["Rtl.WebThreads"].TThreadinfo.$new());
  5517. $mod.TWasmThreadHelper.SetWorkerState.call(aWorker,3);
  5518. Idx = this.FBusyWorkers.indexOf(aWorker);
  5519. if (Idx !== -1) this.FBusyWorkers.splice(Idx,1);
  5520. Idx = this.FIdleWorkers.indexOf(aWorker);
  5521. if (Idx === -1) this.FIdleWorkers = rtl.arrayPushN(this.FIdleWorkers,aWorker);
  5522. if (aCommand !== null) ;
  5523. };
  5524. this.HandleKillCommand = function (aWorker, aCommand) {
  5525. if ((aWorker !== null) && (aCommand !== null)) ;
  5526. };
  5527. this.HandleLoadedCommand = function (aWorker, aCommand) {
  5528. this.DoLog("Entering TThreadController.HandleLoadedCommand");
  5529. $mod.TWasmThreadHelper.SetWorkerState.call(aWorker,3);
  5530. if ($mod.TWasmThreadHelper.GetThreadID.call(aWorker) > 0) this.SendRunCommand(aWorker);
  5531. this.DoLog("Host: exiting TThreadController.HandleLoadedCommand");
  5532. if (aCommand !== null) ;
  5533. };
  5534. this.HandleConsoleCommand = function (aWorker, aCommand) {
  5535. var Prefix = "";
  5536. if (!this.FHandleConsoleMessages) return;
  5537. Prefix = aCommand.senderId;
  5538. if (Prefix === "") {
  5539. Prefix = pas.SysUtils.Format("[Wasm thread %d]: ",pas.System.VarRecs(0,$mod.TWasmThreadHelper.GetThreadID.call(aWorker)))}
  5540. else Prefix = "[" + Prefix + "]: ";
  5541. if (this.FOnConsoleWrite != null) {
  5542. this.FOnConsoleWrite(this,Prefix + aCommand.ConsoleMessage)}
  5543. else pas.System.Writeln(Prefix + aCommand.ConsoleMessage);
  5544. };
  5545. this.InitMessageCallBacks = function () {
  5546. var $with = pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance();
  5547. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdSpawn,rtl.createCallback(this,"HandleRawSpawnCommand"),false);
  5548. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdCleanup,rtl.createCallback(this,"HandleRawCleanupCommand"),false);
  5549. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdKill,rtl.createCallback(this,"HandleRawKillCommand"),false);
  5550. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdCancel,rtl.createCallback(this,"HandleRawCancelCommand"),false);
  5551. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdLoaded,rtl.createCallback(this,"HandleRawLoadedCommand"),false);
  5552. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdConsole,rtl.createCallback(this,"HandleRawConsoleCommand"),false);
  5553. $with.RegisterCommandHandler(pas["Rtl.WebThreads"].cmdReady,rtl.createCallback(this,"HandleRawReadyCommand"),false);
  5554. };
  5555. this.create$1 = function () {
  5556. this.Create$3(pas["Rtl.WebThreads"].DefaultThreadWorker,2);
  5557. return this;
  5558. };
  5559. this.Create$3 = function (aWorkerScript, aSpawnWorkerCount) {
  5560. pas["Rtl.WebThreads"].TWasmThreadController.create$1.call(this);
  5561. this.InitMessageCallBacks();
  5562. this.FThreads = new Object();
  5563. this.FWorkerScript = aWorkerScript;
  5564. this.FInitialWorkerCount = aSpawnWorkerCount;
  5565. this.FMaxWorkerCount = 100;
  5566. return this;
  5567. };
  5568. this.AllocateInitialworkers = function () {
  5569. var I = 0;
  5570. for (var $l = 1, $end = this.FInitialWorkerCount; $l <= $end; $l++) {
  5571. I = $l;
  5572. this.FIdleWorkers.push(this.AllocateNewWorker(this.FWorkerScript));
  5573. };
  5574. };
  5575. this.SpawnThread = function (start_arg) {
  5576. var Result = 0;
  5577. var aInfo = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5578. aInfo.ThreadID = start_arg;
  5579. aInfo.Arguments = start_arg;
  5580. aInfo.OriginThreadID = 0;
  5581. Result = this.SpawnThread$1(pas["Rtl.WebThreads"].TThreadinfo.$clone(aInfo));
  5582. return Result;
  5583. };
  5584. this.SendLoadCommands = function () {
  5585. var WT = null;
  5586. pas.System.Writeln("Send load commands");
  5587. this.DoLog("Sending load command to all workers");
  5588. for (var $in = this.FIdleWorkers, $l = 0, $end = rtl.length($in) - 1; $l <= $end; $l++) {
  5589. WT = $in[$l];
  5590. if ($mod.TWasmThreadHelper.GetWorkerState.call(WT) === 1) this.SendLoadCommand(WT);
  5591. };
  5592. };
  5593. });
  5594. $mod.$implcode = function () {
  5595. $mod.$resourcestrings = {SErrMaxWorkersReached: {org: "Cannot create thread worker, Maximum number of workers (%d) reached."}};
  5596. };
  5597. $mod.$init = function () {
  5598. pas["Rtl.WebThreads"].TWasmThreadController.SetInstanceClass($mod.TThreadController);
  5599. };
  5600. },[]);
  5601. rtl.module("CustApp",["System","Classes","SysUtils","Types","JS"],function () {
  5602. "use strict";
  5603. var $mod = this;
  5604. rtl.createClass(this,"TCustomApplication",pas.Classes.TComponent,function () {
  5605. this.$init = function () {
  5606. pas.Classes.TComponent.$init.call(this);
  5607. this.FExceptObjectJS = undefined;
  5608. this.FTerminated = false;
  5609. this.FOptionChar = "";
  5610. this.FCaseSensitiveOptions = false;
  5611. this.FStopOnException = false;
  5612. this.FExceptionExitCode = 0;
  5613. this.FExceptObject = null;
  5614. };
  5615. this.$final = function () {
  5616. this.FExceptObject = undefined;
  5617. pas.Classes.TComponent.$final.call(this);
  5618. };
  5619. this.Create$1 = function (AOwner) {
  5620. pas.Classes.TComponent.Create$1.call(this,AOwner);
  5621. this.FOptionChar = "-";
  5622. this.FCaseSensitiveOptions = true;
  5623. this.FStopOnException = false;
  5624. return this;
  5625. };
  5626. this.HandleException = function (Sender) {
  5627. var E = null;
  5628. var Tmp = null;
  5629. Tmp = null;
  5630. E = this.FExceptObject;
  5631. if ((E === null) && pas.System.Assigned(this.FExceptObjectJS)) {
  5632. if (rtl.isExt(this.FExceptObjectJS,Error,1)) {
  5633. Tmp = pas.SysUtils.EExternalException.$create("Create$1",[this.FExceptObjectJS.message])}
  5634. else if (rtl.isExt(this.FExceptObjectJS,Object,1) && this.FExceptObjectJS.hasOwnProperty("message")) {
  5635. Tmp = pas.SysUtils.EExternalException.$create("Create$1",["" + this.FExceptObjectJS["message"]])}
  5636. else Tmp = pas.SysUtils.EExternalException.$create("Create$1",[JSON.stringify(this.FExceptObjectJS)]);
  5637. E = Tmp;
  5638. };
  5639. try {
  5640. this.ShowException(E);
  5641. if (this.FStopOnException) this.Terminate$1(this.FExceptionExitCode);
  5642. } finally {
  5643. Tmp = rtl.freeLoc(Tmp);
  5644. };
  5645. if (Sender === null) ;
  5646. };
  5647. this.Run = function () {
  5648. do {
  5649. this.FExceptObject = null;
  5650. this.FExceptObjectJS = null;
  5651. try {
  5652. this.DoRun();
  5653. } catch ($e) {
  5654. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  5655. var E = $e;
  5656. this.FExceptObject = E;
  5657. this.FExceptObjectJS = E;
  5658. this.HandleException(this);
  5659. } else {
  5660. this.FExceptObject = null;
  5661. this.FExceptObjectJS = $e;
  5662. this.HandleException(this);
  5663. }
  5664. };
  5665. break;
  5666. } while (!this.FTerminated);
  5667. };
  5668. this.Terminate$1 = function (AExitCode) {
  5669. this.FTerminated = true;
  5670. rtl.exitcode = AExitCode;
  5671. };
  5672. });
  5673. });
  5674. rtl.module("webworkerbase",["System","JS","weborworker"],function () {
  5675. "use strict";
  5676. var $mod = this;
  5677. });
  5678. rtl.module("webworker",["System","JS","weborworker","webworkerbase"],function () {
  5679. "use strict";
  5680. var $mod = this;
  5681. });
  5682. rtl.module("workerapp",["System","Classes","SysUtils","CustApp","webworker","Rtl.WorkerCommands"],function () {
  5683. "use strict";
  5684. var $mod = this;
  5685. var $impl = $mod.$impl;
  5686. rtl.createClass(this,"TWorkerApplication",pas.CustApp.TCustomApplication,function () {
  5687. this.$init = function () {
  5688. pas.CustApp.TCustomApplication.$init.call(this);
  5689. this.FSendOutputToConsole = false;
  5690. };
  5691. this.Create$1 = function (AOwner) {
  5692. pas.CustApp.TCustomApplication.Create$1.call(this,AOwner);
  5693. this.FSendOutputToConsole = true;
  5694. return this;
  5695. };
  5696. this.ShowException = function (aError) {
  5697. var Ex = null;
  5698. Ex = pas["Rtl.WorkerCommands"].TWorkerExceptionCommandHelper.Create(aError.$classname,aError.fMessage,-1);
  5699. this.SendCommand(Ex);
  5700. };
  5701. this.SendCommand = function (aCommand) {
  5702. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(aCommand);
  5703. };
  5704. });
  5705. $mod.$implcode = function () {
  5706. $impl.EnvNames = null;
  5707. $impl.ReloadEnvironmentStrings = function () {
  5708. var I = 0;
  5709. var S = "";
  5710. var N = "";
  5711. var A = [];
  5712. var P = [];
  5713. if ($impl.EnvNames != null) pas.SysUtils.FreeAndNil({p: $impl, get: function () {
  5714. return this.p.EnvNames;
  5715. }, set: function (v) {
  5716. this.p.EnvNames = v;
  5717. }});
  5718. $impl.EnvNames = new Object();
  5719. S = self.location.search;
  5720. S = pas.System.Copy(S,2,S.length - 1);
  5721. A = S.split("&");
  5722. for (var $l = 0, $end = rtl.length(A) - 1; $l <= $end; $l++) {
  5723. I = $l;
  5724. P = A[I].split("=");
  5725. N = pas.SysUtils.LowerCase(decodeURIComponent(P[0]));
  5726. if (rtl.length(P) === 2) {
  5727. $impl.EnvNames[N] = decodeURIComponent(P[1])}
  5728. else if (rtl.length(P) === 1) $impl.EnvNames[N] = "";
  5729. };
  5730. };
  5731. $impl.MyGetEnvironmentVariable = function (EnvVar) {
  5732. var Result = "";
  5733. var aName = "";
  5734. aName = pas.SysUtils.LowerCase(EnvVar);
  5735. if ($impl.EnvNames.hasOwnProperty(aName)) {
  5736. Result = "" + $impl.EnvNames[aName]}
  5737. else Result = "";
  5738. return Result;
  5739. };
  5740. $impl.MyGetEnvironmentVariableCount = function () {
  5741. var Result = 0;
  5742. Result = rtl.length(Object.getOwnPropertyNames($impl.EnvNames));
  5743. return Result;
  5744. };
  5745. $impl.MyGetEnvironmentString = function (Index) {
  5746. var Result = "";
  5747. Result = "" + $impl.EnvNames[Object.getOwnPropertyNames($impl.EnvNames)[Index]];
  5748. return Result;
  5749. };
  5750. };
  5751. $mod.$init = function () {
  5752. $impl.ReloadEnvironmentStrings();
  5753. pas.SysUtils.OnGetEnvironmentVariable = $impl.MyGetEnvironmentVariable;
  5754. pas.SysUtils.OnGetEnvironmentVariableCount = $impl.MyGetEnvironmentVariableCount;
  5755. pas.SysUtils.OnGetEnvironmentString = $impl.MyGetEnvironmentString;
  5756. };
  5757. },["JS","Types"]);
  5758. rtl.module("wasiworkerapp",["System","Classes","SysUtils","workerapp","wasienv"],function () {
  5759. "use strict";
  5760. var $mod = this;
  5761. rtl.createClass(this,"TWorkerWASIHostApplication",pas.workerapp.TWorkerApplication,function () {
  5762. this._WasiHostClass = null;
  5763. this.$init = function () {
  5764. pas.workerapp.TWorkerApplication.$init.call(this);
  5765. this.FHost = null;
  5766. this.FOnHostCreated = null;
  5767. };
  5768. this.$final = function () {
  5769. this.FHost = undefined;
  5770. this.FOnHostCreated = undefined;
  5771. pas.workerapp.TWorkerApplication.$final.call(this);
  5772. };
  5773. this.RegisterMessageHandlers = function () {
  5774. };
  5775. this.DoRun = function () {
  5776. };
  5777. this.CreateHost = function () {
  5778. var Result = null;
  5779. var C = null;
  5780. C = this._WasiHostClass;
  5781. if (C === null) C = pas.wasienv.TWASIHost;
  5782. Result = C.$create("Create$1",[this]);
  5783. return Result;
  5784. };
  5785. this.DoHostCreated = function () {
  5786. if (this.FOnHostCreated != null) this.FOnHostCreated(this);
  5787. };
  5788. this.Create$1 = function (aOwner) {
  5789. pas.workerapp.TWorkerApplication.Create$1.call(this,aOwner);
  5790. this.RegisterMessageHandlers();
  5791. this.FHost = this.CreateHost();
  5792. this.DoHostCreated();
  5793. return this;
  5794. };
  5795. this.Destroy = function () {
  5796. pas.SysUtils.FreeAndNil({p: this, get: function () {
  5797. return this.p.FHost;
  5798. }, set: function (v) {
  5799. this.p.FHost = v;
  5800. }});
  5801. pas.Classes.TComponent.Destroy.call(this);
  5802. };
  5803. this.SetWasiHostClass = function (aClass) {
  5804. $mod.TWorkerWASIHostApplication._WasiHostClass = aClass;
  5805. };
  5806. });
  5807. });
  5808. rtl.module("Rtl.threadrunner",["System","Classes","SysUtils","JS","webassembly","wasienv","Rtl.WebThreads","Rtl.threadcontroller","Rtl.WorkerCommands","wasiworkerapp"],function () {
  5809. "use strict";
  5810. var $mod = this;
  5811. rtl.createClass(this,"TWorkerThreadRunner",pas["Rtl.WebThreads"].TWasmThreadController,function () {
  5812. this.TWorkerState = {"0": "wsNeutral", wsNeutral: 0, "1": "wsLoading", wsLoading: 1, "2": "wsLoaded", wsLoaded: 2, "3": "wsRunWaiting", wsRunWaiting: 3, "4": "wsRunning", wsRunning: 4};
  5813. this.$init = function () {
  5814. pas["Rtl.WebThreads"].TWasmThreadController.$init.call(this);
  5815. this.FOnRunThread = null;
  5816. this.FState = 0;
  5817. this.FCurrentThreadInfo = pas["Rtl.WebThreads"].TThreadinfo.$new();
  5818. this.FThreadEntryPoint = "";
  5819. this.FLastSenderID = "";
  5820. };
  5821. this.$final = function () {
  5822. this.FOnRunThread = undefined;
  5823. this.FCurrentThreadInfo = undefined;
  5824. pas["Rtl.WebThreads"].TWasmThreadController.$final.call(this);
  5825. };
  5826. this.RawRunWasmModule = function (aCommand) {
  5827. this.RunWasmModule(aCommand);
  5828. };
  5829. this.RawCancelWasmModule = function (aCommand) {
  5830. this.CancelWasmModule(aCommand);
  5831. };
  5832. this.RegisterCommands = function () {
  5833. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterCommandHandler(pas["Rtl.WebThreads"].cmdRun,rtl.createCallback(this,"RawRunWasmModule"),false);
  5834. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterCommandHandler(pas["Rtl.WebThreads"].cmdCancel,rtl.createCallback(this,"RawCancelWasmModule"),false);
  5835. };
  5836. this.HaveWebassembly = function () {
  5837. if (this.FState === 3) {
  5838. this.CallRunWebAssemblyThread()}
  5839. else this.FState = 2;
  5840. };
  5841. this.CallRunWebAssemblyThread = function () {
  5842. if (this.FOnRunThread != null) this.FOnRunThread(rtl.createCallback(this,"DoRunThread"));
  5843. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().FDefaultSenderID = this.FLastSenderID;
  5844. };
  5845. this.DoRunThread = function (aExports) {
  5846. var aResult = 0;
  5847. try {
  5848. this.FState = 4;
  5849. aResult = aExports[this.FThreadEntryPoint](this.FCurrentThreadInfo.ThreadID,this.FCurrentThreadInfo.Arguments);
  5850. this.FState = 2;
  5851. if (aResult > 0) this.SendConsoleMessage$1("Thread run function result= %d ",pas.System.VarRecs(0,aResult));
  5852. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(pas["Rtl.WebThreads"].TWorkerCleanupCommandHelper.Create(this.FCurrentThreadInfo.ThreadID,aResult));
  5853. } catch ($e) {
  5854. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  5855. var E = $e;
  5856. this.SendException(E);
  5857. } else if (rtl.isExt($e,Error)) {
  5858. var JE = $e;
  5859. this.SendException$1(JE);
  5860. } else if (rtl.isExt($e,Error)) {
  5861. var JE = $e;
  5862. this.SendException$1(JE);
  5863. } else throw $e
  5864. };
  5865. };
  5866. this.RunWasmModule = function (aCommand) {
  5867. if (this.FState === 0) {
  5868. this.DoLog("No webassembly loaded");
  5869. return;
  5870. };
  5871. if (this.FState in rtl.createSet(4,3)) {
  5872. this.DoLog("Webassembly already running");
  5873. return;
  5874. };
  5875. this.FCurrentThreadInfo.ThreadID = aCommand.ThreadID;
  5876. this.FCurrentThreadInfo.Arguments = aCommand.Args;
  5877. this.FLastSenderID = pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().FDefaultSenderID;
  5878. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().FDefaultSenderID = "Wasm thread " + pas.SysUtils.IntToStr(this.FCurrentThreadInfo.ThreadID);
  5879. if (this.FState === 2) {
  5880. this.CallRunWebAssemblyThread()}
  5881. else this.FState = 3;
  5882. };
  5883. this.CancelWasmModule = function (aCommand) {
  5884. if (aCommand !== null) ;
  5885. };
  5886. this.SendLoaded = function () {
  5887. var L = null;
  5888. L = pas["Rtl.WebThreads"].TWorkerLoadedCommandHelper.Create();
  5889. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(L);
  5890. };
  5891. this.SendConsoleMessage = function (aMessage) {
  5892. var L = null;
  5893. L = pas["Rtl.WorkerCommands"].TConsoleOutputCommandHelper.create(aMessage);
  5894. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendConsoleCommand(L);
  5895. };
  5896. this.SendConsoleMessage$1 = function (aFmt, aArgs) {
  5897. this.SendConsoleMessage(pas.SysUtils.Format(aFmt,aArgs));
  5898. };
  5899. this.SendException = function (aError) {
  5900. var E = null;
  5901. E = pas["Rtl.WorkerCommands"].TWorkerExceptionCommandHelper.Create(aError.$classname,aError.fMessage,this.FCurrentThreadInfo.ThreadID);
  5902. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(E);
  5903. };
  5904. this.SendException$1 = function (aError) {
  5905. var aMessage = "";
  5906. var aClass = "";
  5907. var E = null;
  5908. aClass = "Error";
  5909. aMessage = aError.message;
  5910. E = pas["Rtl.WorkerCommands"].TWorkerExceptionCommandHelper.Create(aClass,aMessage,this.FCurrentThreadInfo.ThreadID);
  5911. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(E);
  5912. };
  5913. this.Reset = function () {
  5914. this.FState = 0;
  5915. };
  5916. this.Loading = function () {
  5917. this.FState = 1;
  5918. };
  5919. this.create$1 = function () {
  5920. pas["Rtl.WebThreads"].TWasmThreadController.create$1.call(this);
  5921. this.FThreadEntryPoint = pas["Rtl.WebThreads"].DefaultThreadEntryPoint;
  5922. this.RegisterCommands();
  5923. return this;
  5924. };
  5925. this.SpawnThread = function (start_arg) {
  5926. var Result = 0;
  5927. var P = null;
  5928. P = pas["Rtl.WebThreads"].TWorkerSpawnThreadCommandHelper.Create(start_arg,start_arg);
  5929. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(P);
  5930. Result = start_arg;
  5931. return Result;
  5932. };
  5933. });
  5934. rtl.createClass(this,"TWorkerThreadRunnerApplication",pas.wasiworkerapp.TWorkerWASIHostApplication,function () {
  5935. this.RawLoadWasmModule = function (aCommand) {
  5936. this.LoadWasmModule(aCommand);
  5937. };
  5938. this.GetThreadSupport = function () {
  5939. var Result = null;
  5940. Result = $mod.GlobalWorkerThreadRunner();
  5941. return Result;
  5942. };
  5943. this.LoadWasmModule = function (aCommand) {
  5944. var $Self = this;
  5945. var WASD = pas.wasienv.TWebAssemblyStartDescriptor.$new();
  5946. var aTable = null;
  5947. function doOK(aValue) {
  5948. var Result = undefined;
  5949. Result = true;
  5950. WASD.Instance = aValue;
  5951. WASD.Exported = aValue.exports;
  5952. WASD.CallRun = null;
  5953. $Self.FHost.PrepareWebAssemblyInstance(pas.wasienv.TWebAssemblyStartDescriptor.$clone(WASD));
  5954. return Result;
  5955. };
  5956. function DoFail(aValue) {
  5957. var Result = undefined;
  5958. var E = null;
  5959. $Self.GetThreadSupport().Reset();
  5960. Result = true;
  5961. E = pas.SysUtils.Exception.$create("Create$1",["Failed to create webassembly. Reason: " + JSON.stringify(aValue)]);
  5962. $Self.GetThreadSupport().SendException(E);
  5963. E = rtl.freeLoc(E);
  5964. return Result;
  5965. };
  5966. this.GetThreadSupport().Loading();
  5967. try {
  5968. aTable = new WebAssembly.Table(pas.webassembly.TJSWebAssemblyTableDescriptor.$clone(this.FHost.FTableDescriptor));
  5969. WASD.$assign(this.FHost.InitStartDescriptor(aCommand.Memory,aTable,null));
  5970. WASD.Module = aCommand.Module;
  5971. WebAssembly.instantiate(aCommand.Module,WASD.Imports).then(doOK,DoFail).catch(DoFail);
  5972. } catch ($e) {
  5973. if (pas.SysUtils.Exception.isPrototypeOf($e)) {
  5974. var E = $e;
  5975. this.GetThreadSupport().SendException(E);
  5976. } else if (rtl.isExt($e,Error)) {
  5977. var JE = $e;
  5978. this.GetThreadSupport().SendException$1(JE);
  5979. } else throw $e
  5980. };
  5981. };
  5982. this.Create$1 = function (aOwner) {
  5983. pas.wasiworkerapp.TWorkerWASIHostApplication.Create$1.call(this,aOwner);
  5984. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().RegisterCommandHandler(pas["Rtl.WebThreads"].cmdLoad,rtl.createCallback(this,"RawLoadWasmModule"),false);
  5985. pas["Rtl.WorkerCommands"].TCommandDispatcher.GetInstance().SendCommand$2(pas["Rtl.WebThreads"].TWorkerReadyCommandHelper.Create());
  5986. return this;
  5987. };
  5988. });
  5989. rtl.createClass(this,"TWASIThreadRunnerHost",pas.wasienv.TWASIHost,function () {
  5990. this.GetThreadSupport = function () {
  5991. var Result = null;
  5992. Result = $mod.GlobalWorkerThreadRunner();
  5993. return Result;
  5994. };
  5995. this.RunWebAssemblyThread = function (aProc) {
  5996. this.RunWebAssemblyInstance(null,null,aProc);
  5997. };
  5998. this.DoStdWrite = function (Sender, aOutput) {
  5999. this.GetThreadSupport().SendConsoleMessage(aOutput);
  6000. };
  6001. this.DoAfterInstantiate = function () {
  6002. pas.wasienv.TWASIHost.DoAfterInstantiate.call(this);
  6003. this.GetThreadSupport().FOnRunThread = rtl.createCallback(this,"RunWebAssemblyThread");
  6004. this.GetThreadSupport().SetWasmModuleAndMemory(this.FPreparedStartDescriptor.Module,this.FPreparedStartDescriptor.Memory);
  6005. this.GetThreadSupport().SendLoaded();
  6006. };
  6007. this.CreateWasiEnvironment = function () {
  6008. var Result = null;
  6009. Result = pas.wasienv.TWASIHost.CreateWasiEnvironment.call(this);
  6010. pas["Rtl.WebThreads"].TWasmThreadSupportApi.$create("Create$1",[Result]);
  6011. return Result;
  6012. };
  6013. });
  6014. this.GlobalWorkerThreadRunner = function () {
  6015. var Result = null;
  6016. Result = rtl.as(pas["Rtl.WebThreads"].TWasmThreadController.GetInstance(),$mod.TWorkerThreadRunner);
  6017. return Result;
  6018. };
  6019. $mod.$init = function () {
  6020. pas.wasiworkerapp.TWorkerWASIHostApplication.SetWasiHostClass($mod.TWASIThreadRunnerHost);
  6021. pas["Rtl.WebThreads"].TWasmThreadController.SetInstanceClass($mod.TWorkerThreadRunner);
  6022. };
  6023. });
  6024. rtl.module("program",["System","Classes","Rtl.threadrunner"],function () {
  6025. "use strict";
  6026. var $mod = this;
  6027. rtl.createClass(this,"TApplication",pas["Rtl.threadrunner"].TWorkerThreadRunnerApplication,function () {
  6028. });
  6029. this.App = null;
  6030. $mod.$main = function () {
  6031. $mod.App = $mod.TApplication.$create("Create$1",[null]);
  6032. $mod.App.Run();
  6033. };
  6034. });
  6035. rtl.run();
  6036. //# sourceMappingURL=pas2jsthreadworker.js.map